Home > Web Front-end > JS Tutorial > How to judge when js script is loaded_javascript skills

How to judge when js script is loaded_javascript skills

WBOY
Release: 2016-05-16 16:57:49
Original
1352 people have browsed it

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:

1. In the interactive state, users can participate in interactions.
2. Opera actually supports js.onreadystatechange, but its state is very different from that of IE.

Copy code The code is as follows:

<script> <p>function include_js(file) {<br> var _doc = document.getElementsByTagName('head')[0];<br> var js = document.createElement('script');<br> js.setAttribute(' type', 'text/javascript');<br> js.setAttribute('src', file);<br> _doc.appendChild(js);</p> <p> if (!/*@cc_on!@*/0) { //if not IE<br> //Firefox2, Firefox3, Safari3.1, Opera9.6 support js.onload<br> js.onload = function () {<br>                 alert('Firefox2, Firefox3,  Safari3.1 , Opera9.6 support js.onload'); 🎜> js.onreadystatechange = function () {<br> if (js.readyState == 'loaded' || js.readyState == 'complete') {<br> alert('IE6, IE7 support js.onreadystatechange') ;<br>                                                                                  <br> return false;<br>}<br> <br><br>include_js('http://www.planabc.net/wp-includes/js/jquery/jquery.js');<br></script>


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template