In the "loading on demand" requirement, we often judge that when the script is loaded, a callback function is returned. So how do we judge that the script is loaded?
We can use onload to judge the loaded JS object (js.onload). This method can be well supported by Firefox2, Firefox3, Safari3.1+, and Opera9.6+ browsers, but IE6 and IE7 do not. Curve saves the country - IE6, IE7 We can use js.onreadystatechange to track the changes in each state (usually 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. .
A supplementary note is needed for the readyState status:
1. In the interactive state, users can participate in the interaction.
2. Opera actually supports js.onreadystatechange, but its status is very different from that of IE.
The code copy is as follows:
<script>
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;
}
include_js('http://www.planabc.net/wp-includes/js/jquery/jquery.js');
</script>