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?1.1.11"); loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js?1.1.11") loadjs("http://bootboxjs.com/bootbox.js?1.1.11") 《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?1.1.11",function(){ loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js?1.1.11",function(){ loadjs("http://bootboxjs.com/bootbox.js?1.1.11") }) }); 《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?1.1.11",function(){ loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js?1.1.11",function(){ loadjs("http://bootboxjs.com/bootbox.js?1.1.11",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.