JavaScript 之 动态加载JS代码或JS文件

时间:2022-12-20 08:07:02

2、动态加载JS文件

<script type="text/javascript">
function loadScript(url, callback) {
  var script = document.createElement("script");
  script.type = "text/javascript";
  if(typeof(callback) != "undefined"){
     if (script.readyState) {
        script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
           script.onreadystatechange = null;
           callback();
        }
    };
  } else {
      script.onload = function () {
        callback();
      };
    }
  }
  script.src = url;
  document.body.appendChild(script);
}
loadScript("jquery-latest.js", function () { //加载,并执行回调函数
  alert($(window).height());
});
//loadScript("jquery-latest.js"); //加载js文件
</script>