if(this.isIE) {
js.onreadystatechange=function (){if(js.readyState=="loaded" || js.readyState=="complete") callback();}
}else{js.onload=function(){callback();}}
js.onerror=function(){alert('Not Found (404): ' src)}//chrome
JS determines whether the script is loaded In the requirement of "on-demand loading", we often judge that when the script is loaded, a callback function is returned. So how to judge that the script is loaded?
We can use onload to determine the loaded JS object (js.onload). This method is well supported by Firefox2, Firefox3, Safari3.1, and Opera9.6 browsers, but is not supported by IE6 and IE7. Curve to save the country - IE6, IE7 We can use js.onreadystatechange to track each state change (generally loading, loaded, interactive, complete). When the return status is loaded or complete, it means that the loading is completed and the callback function is returned. .
An additional explanation is needed for the readyState state:
In the interactive state, users can participate in interactions.
Opera actually supports js.onreadystatechange, but its state is very different from that of IE.
The specific implementation code is as follows:
function include_js(file ) {
var _doc = document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type', 'text/javascript ');
js.setAttribute('src', file);
_doc.appendChild(js);
if (!/*@cc_on!@*/0) { //if not IE
//Firefox2, Firefox3, Safari3.1, Opera9.6 support js.onload
js.onload = function () {
alert('Firefox2, Firefox3, Safari3.1, Opera9.6 support js. onload');
}
} else {
//IE6, IE7 support js.onreadystatechange
js.onreadystatechange = function () {
if (js.readyState == 'loaded' || js.readyState == 'complete') {
alert('IE6, IE7 support js.onreadystatechange');
}
}
}
return false;
}
//execution function
include_js('http://www.jb51.net/jslib//jquery/jquery.js');
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