DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> jQuery入門知識 >> JQuery特效代碼 >> javascript loadScript異步加載腳本示例講解
javascript loadScript異步加載腳本示例講解
編輯:JQuery特效代碼     

一、語法:
loadScript(url[,callback])
或者
loadScript(settings)
二、settings支持的參數:
url:腳本路徑
async:是否異步,默認false(HTML5)
charset:文件編碼
cache:是否緩存,默認為true
success:加載成功後執行的函數,優先執行callback。
三、調用舉例:
. 代碼如下:
//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(“load”, callback, false) : script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) {
script.onreadystatechange = null
callback()
}
}
}
}

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved