This article describes how to asynchronously load scripts in javascript and trigger callback functions. It can be used when loading remote data. The following provides sample code and source code.
I. Syntax:
LoadScript (url [, callback])
Or
LoadScript (settings)
2. Parameters supported by settings:
Url: script path
Async: asynchronous or not. The default value is false (HTML5)
Charset: file encoding
Cache: whether to cache. The default value is true.
Success: the function that is executed after the load is successful. callback is executed first.
Iii. Call example:
The Code is as follows:
// LoadScript (url [, callback])
LoadScript ("http://code.jquery.com/jquery.js ");
LoadScript ("http://code.jquery.com/jquery.js#,function (){
Console. log (1)
});
// LoadScript (settings)
LoadScript ({"url": "parts });
LoadScript ({"url": "loads (){
Console. log (2)
}});
// Or you can set the sauce purple:
// LoadScript (settings [, callback])
LoadScript ({"url": "http://code.jquery.com/jquery.js?,?async=:false,?charset=:=8}},function (){
Console. log ($)
});
4. Source Code:
The Code is as follows:
Function loadScript (url, callback ){
Var head = document. head | document. getElementsByTagName ("head") [0] | document.doc umentElement,
Script,
Options,
If (typeof url = "object "){
Options = url;
Url = undefined;
}
S = options | {};
Url = url | s. url;
Callback = callback | s. success;
Script = document. createElement ("script ");
Script. async = s. async | false;
Script. type = "text/javascript ";
If (s. charset ){
Script. charset = s. charset;
}
If (s. cache = false ){
Url = url + (/\? /. Test (url )? "&": "?" ) + "_ =" + (New Date (). getTime ();
}
Script. src = url;
Head. insertBefore (script, head. firstChild );
If (callback ){
Document. addEventListener? Script. addEventListener ("load", callback, false): script. onreadystatechange = function (){
If (/loaded | complete/. test (script. readyState )){
Script. onreadystatechange = null
Callback ()
}
}
}
}