Home >Web Front-end >JS Tutorial >javascript loadScript asynchronous loading script example explanation_jquery

javascript loadScript asynchronous loading script example explanation_jquery

WBOY
WBOYOriginal
2016-05-16 17:15:131763browse

1. Syntax:
loadScript(url[,callback])
or
loadScript(settings)
2. Parameters supported by settings:
url: script path
async: whether to be asynchronous, default is false (HTML5)
charset: file encoding
cache: whether to cache, default is true
success: function executed after successful loading , execute callback first.
3. Call example:

Copy code 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":"http://code. jquery.com/jquery.js","async":false,"charset":"utf-8","cache":false});
loadScript({"url":"http://code. jquery.com/jquery.js","async":false,"charset":"utf-8","success":function(){
console.log(2)
}});
//Or you can Jiangzi:
//loadScript(settings[,callback])
loadScript({"url":"http://code.jquery.com/jquery.js","async ”:false,”charset”:”utf-8″},function(){
console.log($)
});

4. Source code :
Copy code The code is as follows:

function loadScript(url,callback) {
var head = document.head || document.getElementsByTagName(“head”)[0] || document.documentElement,
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()
}
}
}
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn