Home  >  Article  >  Web Front-end  >  jquery dynamic loading js file implementation steps

jquery dynamic loading js file implementation steps

php中世界最好的语言
php中世界最好的语言Original
2018-04-23 11:35:133437browse

This time I will bring you jquery the steps to implement dynamic loading of js files, what are the precautions for jquery to dynamically load js files, the following is a practical case, let's take a look.

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文件");
});

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>

I believe you have already read the case in this article After mastering the method, please pay attention to other related articles on the php Chinese website for more exciting content!

Recommended reading:

Detailed explanation of the use of jquery plug-in uploadify

Detailed explanation of the use of jQuery to let browsers jump to each other and pass parameters

Detailed explanation of the basic knowledge points of jquery

The above is the detailed content of jquery dynamic loading js file implementation steps. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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