Home >Web Front-end >JS Tutorial >jquery dynamic loading js file implementation steps
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!