我尝试编写一个JavaScript函数,用于加载js脚本(
我的问题是,如果脚本已经加载,则不会执行回调函数。这是错误的。
如何知道脚本是否已经加载?
src
),当脚本加载完成时执行一些回调。同时我会检查是否存在具有相同 src
的脚本。我的问题是,如果脚本已经加载,则不会执行回调函数。这是错误的。
如何知道脚本是否已经加载?
importScript: (function (head) {
function loadError(error) {
throw new URIError("The script " +
error.target.src + " is not accessible.");}
return function (url, callback) {
var existingScript = document.querySelectorAll("script[src='" +
url + "']");
var isNewScript = (existingScript.length == 0);
var script;
if (isNewScript) {
script = document.createElement("script")
script.type = "text/javascript";
}
else {
script = existingScript[0];
}
script.onerror = loadError;
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" ||
script.readyState == "complete") {
script.onreadystatechange = null;
if (callback) {
callback(); }
}
};
} else { // others than IE
script.onload = callback; }
if (isNewScript) {
script.src = url;
head.appendChild(script); }
}
})(document.head || document.getElementsByTagName("head")[0])
据我所知,script.readyState == "loaded" || script.readyState == "complete"
只能在IE浏览器中使用,而在其他浏览器中并不适用...
用法:
importScript("myScript1.js");
importScript("myScript2.js", /* onload function: */
function () { alert("The script has been OK loaded."); });
callback
中传递的参数以检测脚本是否已经加载? - Teemu