English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Several Methods of Not Using script to Import JS Files

Method one: 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(){
        // Wait for the 'load' event of s to complete loading to prevent errors from being called before loading is complete
        console.log(hello);
      )
      setTimeout(function(){//Or use a timer to ensure that it is called after loading (not safe, it is better to listen to events)
        console.log(hello);
      ,1000);
     // $.getScript("abc.js");
  </script>

Method two: 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"');//This function is in new.js, and it runs when click is clicked
});
});
});
</script> 
</head> 
<body> 
<button type="button" id="loadButton">Load</button>
 

Method three: require.js

require.js sharing2.1.1version, note that it is for large projects, in most cases, you can use jQuery.

index.html

<!--Set the entry file main, the js can be omitted-->
<script data-main="main" src="require.js"></script>

main.js

console.log("Hello World");
require(["js1","js2","js3],function () {
  // It is asynchronous loading import. The js suffix can be omitted
  console.log("Have you loaded yet?");
  var total = num1+num2+num3;
  console.log(total);
  hello1();
  hello2();
  hello3();
)

Importing js files with requireJs is very convenient, but pay attention to the conflict of variable names and method names in js files. The cause is that the js files in the browser share the global scope, and the variable names and method names in the scope may be overwritten.

You May Also Like