Home > Article > Web Front-end > How to dynamically load js files using jquery and js_javascript skills
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文件"); });
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>
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.