This article mainly helps you understand the dynamic loading of Javascript files and solves the errors during dynamic loading of Javascript files, if you are interested, you can refer to the dynamic loading of Javascript files, which has always been a problem. for example, it is common to upload files over the Internet:
function loadjs(fileurl){ var sct = document.createElement("script"); sct.src = fileurl; document.head.appendChild(sct);}
Then let's test the result:
《script》 function loadjs(fileurl){ var sct = document.createElement("script"); sct.src = fileurl; document.head.appendChild(sct); } loadjs("http://code.jquery.com/jquery-1.12.0.js?7.1.1"); loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js?7.1.1") loadjs("http://bootboxjs.com/bootbox.js?7.1.1") 《script》
After the code is loaded, the following error occurs:
Jquery is loaded in the first processing. Why does it still report that jQuery does not exist?
Because loading like this is equivalent to opening three threads, but the jquery file starts the thread first, and the time when jquery finishes executing the thread exceeds the next two times. therefore, the jquery object may not be found after execution.
But how does this approach work?
In fact, File loading is handled in a state. File loading has an onload event, which can be used to monitor whether the file is loaded.
Therefore, we can consider this method to process the desired results. we can handle the results in an intuitive way. The improved code is as follows:
《script》 function loadjs(fileurl, fn){ var sct = document.createElement("script"); sct.src = fileurl; if(fn){ sct.onload = fn; } document.head.appendChild(sct); } loadjs("http://code.jquery.com/jquery-1.12.0.js?7.1.1",function(){ loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js?7.1.1",function(){ loadjs("http://bootboxjs.com/bootbox.js?7.1.1") }) }); 《script》
OK. after the code is executed, the file will be loaded only after the previous loading is completed, so that the object cannot be found.
Then we will execute the effect of a pop-up box. the Bootbox. js plug-in is used in the code. the loading code is as follows:
loadjs("http://code.jquery.com/jquery-1.12.0.js?7.1.1",function(){ loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js?7.1.1",function(){ loadjs("http://bootboxjs.com/bootbox.js?7.1.1",function(){ bootbox.alert("Hello world!", function() { Example.show("Hello world callback"); }); }) }) });
Refresh the page and the pop-up box is displayed:
Code loaded dynamically often takes a lot of time to debug. the best way is to write a simple example to understand the reasons. the code here can be encapsulated and loaded with CSS files. as your own plug-in.