Summary of various solutions for dynamically loading js files in javascript
- 2020-03-29 23:45:41
- OfStack
A comparison is all in the dynamic plus method
var webJsBase = {
require: function(libraryName) {
document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
},
load: function(defaultLoad) {
if((typeof Prototype=='undefined')||(typeof Element == 'undefined')||(typeof Element.Methods=='undefined'))
throw ('prototype lib Load failed! ');
if(typeof defaultLoad=='undefined')defaultLoad='';
var js = /webJsBase.js(?.*)?$/;
$$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, '');
var includes = s.src.match(/?.*load=([a-zA-Z0-9_,]*)/);
(includes ? includes[1] : defaultLoad).split(',').each(function(include) {
webJsBase.require(path + include + '.js');
});
});
}
};
webJsBase.load(); //Here the parameter can specify the js file to be loaded by default
This is the easiest way to load and then reuse direct document.write as shown below.
<script language="javascript">
document.write("<script src='test.js'></script>");
</script>
Add an id to the script and dynamically change the SRC attribute of the existing script
<script src='' id="s1"></script>
<script language="javascript">
s1.src="test.js"
</script>
This USES getElementsByTagName('HEAD') to dynamically create script elements
<script>
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src="test.js";
oHead.appendChild( oScript);
</script>
You can also try this, and specify a function
function include(src) {
HTMLCode = '<script language="javascript" src="' + src + '"></script>';
document.write(HTMLCode);
}
Call the method so it looks like your PHP include function
include(baseDir + "/Prototype.js");
include(baseDir + "/Map.js");
include(baseDir + "/MapEvent.js");
include(baseDir + "/model/MapModel.js");
include(baseDir + "/model/MapType.js");
include(baseDir + "/model/Tile.js");
Some friends said that you can use ExtJs4 dynamic loading js here I will not introduce, the above method is enough to let you achieve dynamic loading js.
Therefore, while using this method to load Js dynamically, the Js script of the main interface continues to execute, so it is possible that the Js code loaded asynchronously will not get the expected effect.
This is a good time to consider using Ajax to load Js.