javascript loadScript異步加載腳本示例講解
一、語法:
loadScript(url[,callback])
或者
loadScript(settings)
二、settings支持的參數(shù):
url:腳本路徑
async:是否異步,默認(rèn)false(HTML5)
charset:文件編碼
cache:是否緩存,默認(rèn)為true
success:加載成功后執(zhí)行的函數(shù),優(yōu)先執(zhí)行callback。
三、調(diào)用舉例:
//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)
}});
//或者你可以醬紫:
//loadScript(settings[,callback])
loadScript({“url”:”http://code.jquery.com/jquery.js”,”async”:false,”charset”:”utf-8″},function(){
console.log($)
});
四、源代碼:
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(“l(fā)oad”, callback, false) : script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) {
script.onreadystatechange = null
callback()
}
}
}
}
相關(guān)文章
jquery中的mouseleave和mouseout的區(qū)別 模仿下拉框效果
不論鼠標(biāo)指針離開被選元素還是任何子元素,都會觸發(fā) mouseout 事件,只有在鼠標(biāo)指針離開被選元素時,才會觸發(fā) mouseleave 事件2012-02-02
jquery清空textarea等輸入框?qū)崿F(xiàn)代碼
jquery清空textarea等輸入框在工作中很常見,接下來的代碼簡單實(shí)用,感興趣的朋友可以參考下哈,希望對你有所幫助2013-04-04
JQuery+CSS提示框?qū)崿F(xiàn)思路及代碼(純手工打造)
純手工打造、兼容性還哦可、可移植任何項目感興趣的朋友可以學(xué)習(xí)下,希望對你的jquery提升有所幫助2013-05-05
jQuery+Ajax實(shí)現(xiàn)限制查詢間隔的方法
這篇文章主要介紹了jQuery+Ajax實(shí)現(xiàn)限制查詢間隔的方法,涉及jQuery的ajax方法參數(shù)設(shè)置及asp.net后臺交互的相關(guān)技巧,需要的朋友可以參考下2016-06-06
jquery操作select取值賦值與設(shè)置選中實(shí)例
下面小編就為大家?guī)硪黄猨query操作select取值賦值與設(shè)置選中實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
jQuery-App輸入框?qū)崿F(xiàn)實(shí)時搜索
這篇文章主要為大家詳細(xì)介紹了jQuery-App輸入框?qū)崿F(xiàn)實(shí)時搜索,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-11-11

