Home > Article > Web Front-end > Comment on 4 ways to asynchronously load js_javascript skills
4 ways to asynchronously load js, the review begins.
Option 1: $(document).ready
<!DOCTYPE html> <html> <head> <script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { alert("加载完成!"); }); </script> </head> <body> <img src="http://images.cnitblog.com/i/121863/201405/222202573569862.jpg" /> </body> </html>
Comments:
1. Need to quote jquery
2. Compatible with all browsers.
Option 2: 3f1c4e4b6b16bbbd69b2ee476dc4f83a async="async" attribute of tag
The definition and usage of async (it is an attribute of HTML5)
The async attribute specifies that once the script is available, it will be executed asynchronously.
Example:
<script type="text/javascript" src="xxxxxxx.js" async="async"></script>
Comments:
1. The new attributes in HTML5 are supported by Chrome, FF, IE9 & IE9+ (IE6~8 are not supported). Additionally, this approach does not guarantee that the scripts will be executed in order.
2. The async attribute only applies to external scripts (only when using the src attribute).
Option 3: 3f1c4e4b6b16bbbd69b2ee476dc4f83a defer="defer" attribute of tag
Thedefer attribute specifies whether to defer script execution until the page is loaded.
Some javascript scripts use the document.write method to create the current document content, but other scripts may not.
If your script does not change the content of the document, you can add the defer attribute to the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag to speed up processing of the document. Because the browser knows that it will be able to safely read the remainder of the document without executing the script, it will defer interpretation of the script until the document has been displayed to the user.
Example:
<script type="text/javascript" defer="defer"> alert(document.getElementById("p1").firstChild.nodeValue); </script>
Comments: Compatible with all browsers. Additionally, this approach ensures that all scripts that set the defer attribute are executed in order.
Option 4: Dynamic creation of 3f1c4e4b6b16bbbd69b2ee476dc4f83a tags
Example:
<!DOCTYPE html> <html> <head> <script type="text/javascript"> (function(){ var s = document.createElement('script'); s.type = 'text/javascript'; s.src = "http://code.jquery.com/jquery-1.7.2.min.js"; var tmp = document.getElementsByTagName('script')[0]; tmp.parentNode.insertBefore(s, tmp); })(); </script> </head> <body> <img src="http://images.cnitblog.com/i/121863/201405/222202573569862.jpg" /> </body> </html>
Comments: Compatible with all browsers.
The above is a differentiated introduction to the four methods of js asynchronous loading. I hope it will be helpful to everyone in learning js asynchronous loading.