Home > Web Front-end > JS Tutorial > How to dynamically load js files using jquery and js_javascript skills

How to dynamically load js files using jquery and js_javascript skills

WBOY
Release: 2016-05-16 15:18:56
Original
1089 people have browsed it

The example in this article describes how jquery and js implement dynamic loading of js files. Share it with everyone for your reference, the details are as follows:

Question:

If you use jquery append to load the script tag directly, an error will be reported. In addition to document.write, is there any other better way to dynamically load js files?

Solution:

1. jquery method

$.getScript("./test.js");  //加载js文件
$.getScript("./test.js",function(){  //加载test.js,成功后,并执行回调函数
  console.log("加载js文件");
});

Copy after login

2. js method

<html>
<body>
</body>
</html>
<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>

Copy after login

Readers who are interested in more JavaScript-related content can check out the special topics on this site: "Summary of JavaScript Errors and Debugging Techniques" and "Summary of JavaScript Extension Techniques"

I hope this article will be helpful to everyone in JavaScript programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template