Home >Web Front-end >JS Tutorial >Several ways to import js files without using scripts
Method 1: Native
adc.js content is as follows:
var hello = "H9";
html.html
<script> var s = document.createElement("script"); s.src = "abc.js"; document.head.appendChild(s); s.addEventListener("load",function(){ // 等待s的load事件加载完响应,防止未加载完就调用出错 console.log(hello); }) setTimeout(function(){//或者使用定时器保证其载入完后调用(不安全,不如监听事件好) console.log(hello); },1000); // $.getScript("abc.js"); </script>
Method 2: jquery.js
$.getScript("abc.js",function(){ alert("heheheh"); console.log(hello); });
<script type="text/javascript" src="../jquery.js"></script> <script type="text/javascript"> $(function() { $('#loadButton').click(function(){ $.getScript('new.js',function(){ newFun('"Checking new script"');//这个函数是在new.js里面的,当点击click后运行这个函数 }); }); }); </script> </head> <body> <button type="button" id="loadButton">Load</button>
Method 3 :require.js
require.js shares version 2.1.1. Note that it is for use in large projects. In this case, just use jquery.
index.html
a29ebcf9794772d5cab47327b0bcf85e
8f4d94d1c8df4a18a94a14a0d9c7843b2cacc6d41bbb37262a98f745aa00fbf0
main.js
console.log("你好世界"); require(["js1","js2","js3"],function () { // 是异步加载导入。js后缀可以省略 console.log("你们加载完了么?"); var total = num1+num2+num3; console.log(total); hello1(); hello2(); hello3(); })
Using requireJs can easily import js files, but you should pay attention to the problem of variable name and method name conflicts in js files. Cause: Browser js files share the global scope, and variable names and method names in the scope may be overwritten