Keywords: induction load (async loading), delay loading (lazy loading), performs delay (lazy execution), async attribute, defer properties
<script src="http://yourdomain.com/script.js"></script>
2. Common asynchronous loading (Script DOM Element)
(function() { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'http://yourdomain.com/script.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })();
Also known as non-blocking asynchronous loading, the browser at the same time, will continue to process subsequent pages in the download execution js.
(function() { var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
(function() {var po = document.createElement("script"); po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s); })();
However, this loading before loading will stop executing the trigger onload event , and now many pages of code to perform additional rendering work even when onload and so on, so you'll block the initial processing of the page.
Asynchronous loading at 3. onload
(function() { function async_load(){ var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'http://yourdomain.com/script.js'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); } if (window.attachEvent) window.attachEvent('onload', async_load); else window.addEventListener('load', async_load, false); })();
- DOMContentLoaded: page (document) has been parsed, dom element on the page is already available. But the page referenced in the picture, subframe may not have been loaded.
- OnLoad: all resources are loaded pages (including pictures). Browser loading progress stopped at this time.
function loadScript(url, callback){ var script = document.createElement_x("script") script.type = "text/javascript"; if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others: Firefox, Safari, Chrome, and Opera script.onload = function(){ callback(); }; } script.src = url; document.body.appendChild(script); }
5. Other methods of asynchronous loading
Due to the dynamic characteristics of Javascript, there are many asynchronous loading method:
- XHR Eval
- XHR Injection
- Script in Iframe
- Script Defer
- document.write Script Tag
- Another method is to 0 seconds delay in combination with other methods used setTimeout.
XHR Eval: js access to content through ajax, then eval execution.
var xhrObj = getXHRObject(); xhrObj.onreadystatechange = function() { if ( xhrObj.readyState != 4 ) return; eval(xhrObj.responseText); }; xhrObj.open('GET', 'A.js', true); xhrObj.send('');
<span style="font-size: small;"> var xhr = new XMLHttpRequest(); xhr.open("get","load.js",true); xhr.onreadystatechange=function(){ if(readyState==4){ if(status>=200&&status<300||status==304){ var script = document.createElement("script"); script.type = "text/javascript"; script.src = xhr.responseText; document.body.appendChild(script); } } } xhr.send(null);
</span>
Script in Iframe: create and insert an iframe element, let asynchronous execution js
var iframe = document.createElement('iframe'); document.body.appendChild(iframe); var doc = iframe.contentWindow.document; doc.open().write('<body onload="insertJS()">'); doc.close();
Mobile GMail : js contents page is annotated, so it will not perform, then when you need to get the script element text content, eval execution after removing the comments.
<script type="text/javascript"> /* var ... */ </script>
See Resources for Velocity Steve Souders General Assembly and Taobao two lectures in 2010.
Two, async and defer attributes
<script src="file.js" defer>
</script>
或
<script type="text/javascript" defer="defer">
alert(document.getElementById("p1").firstChild.nodeValue);
</script>
- Delay execution of the script, script tag is equivalent to the bottom of the body tag into the page, js script will be executed before the DOMContentLoaded document
- In addition to the newer versions of IE and Firefox, other browsers did not support, defer property in IE 4.0 is realized in more than 13 years! Firefox 3.5 from the start to support defer property.
<script src="file.js" async></script>
- async attribute applies only to external script (only when using the src attribute).
- Note: There are several ways to perform an external script:
- If async = "async": script asynchronously with respect to the rest of the page execution (when the page to continue parsing, the script will be executed)
- When the script execution will be completed parsing the page: If you do not use async and defer = "defer"
- If neither async nor defer: Before proceeding to resolve the page in a browser, reads and executes the script immediately
- type attribute is required in HTML 4, the in HTML5 is optional.
- async attribute is new in HTML5.
- Individual attributes (xml: space) is not supported in HTML5.
- No async attribute, script will get immediately (download) and execute before continuing to process the back, blocking the subsequent processing browser during this period.
- If there async attribute, then the script will be downloaded and executed asynchronously, while the browser continues subsequent processing.
- HTML4 in there defer property, which prompted the browser this script will not produce any document element (not document.write), so the browser will continue to follow-up processing and rendering.
- If you do not async attribute but defer attribute, then the script will be executed after the page parse.
- If you set up both, then defer attribute mainly to make async attribute is not supported by older browsers according to the original defer manner, rather than in a synchronized manner.
- The browser will parse and execute them immediately, whether synchronous load After downloading the contents js or asynchronous loading.
- We said earlier asynchronous loading, the solution is just a matter of downloading stage, but the code will be executed immediately after downloading.
- The browser is the stage to perform parsing JS block any operation, when the browser is unresponsive.
<script src=“…”></script>
</head>
- Preventing subsequent download;
- In IE 6-7 in order script is downloaded, rather than the current "parallel download, execution order" fashion;
- Download and stop rendering (rendering) to resolve the implementation phase;
...
<script src=“…”></script>
</body>
- Does not prevent other downloads;
- In IE 6-7 in order script is downloaded;
- Download and stop rendering (rendering) to resolve the implementation phase;
('script');
se.src = 'http://anydomain.com/A.js';
document.getElementsByTagName('head')
[0].appendChild(se);
This article says this is the way.
- Does not prevent other downloads
- In all browsers, script are parallel download
- Just stop rendering (rendering) parsing the implementation phase
- Asynchronous execution on demand Download + (2010)
Image new new SE = var ();
se.onload registerScript = ();
se.src = 'http://anydomain.com/A.js';
separating out and download the analysis execution js js
- Does not prevent other downloads;
- In all browsers, script download are parallel;
- Unblock rendering (rendering) until when really needed;
Sixth, asynchronous loading problems
When loaded asynchronously, you can not use document.write output document content.
In synchronous mode, document.write is the output of the document at the current script is located. In asynchronous mode, the browser continues to process subsequent pages of content, impossible to determine to what should be output document.write position, so asynchronous mode document.write not feasible. And to the page has onload after document.write will then lead to the implementation of the contents of the current page is empty, because it will automatically trigger document.open method.
In fact document.write reputation is not good, the best use.
alternative method:
- Although asynchronous loading can not be used after document.write, but can still perform operations onload dom (dom create or modify dom), so you can achieve some of their own dynamic output. For example, to create a floating element in the page asynchronously, and that its position on the page it does not matter, as long as to create the dom element added to the document can be.
- If the content of the element needs to be generated in a fixed position asynchronous, you can set a fixed position at the dom element as a target, so you know the location, you can modify this element after asynchronous loading.
Here a jquery method
$ (the Document) .ready ( function () { $ ( '# btnLoad1.button') the Click (. function () { $ ( '#header') HTML ( "Loading ...." ); // $ ( '#load_content') .load ( 'http://jqueryui.com/',); $ ( '#load_content') .hide () .load ( 'http://www.baidu.com', function (the responseText , textStatus, the XMLHttpRequest) { // the status of all successfully perform this function, the display data // textStatus four states success, error, NotModified, timeout IF (textStatus == "error" ) { var MSG = "error:" ; $('#header').html(msg + XMLHttpRequest.status + " " + XMLHttpRequest.statusText); } else if (textStatus == "timeout") { var msg = "操时: "; $('#header').html(msg + XMLHttpRequest.status + " " + XMLHttpRequest.statusText); } else { $('#header').html("加载完成"); $(this).fadeIn(); } }); }); });
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>JQuery - Load</title> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Expires" content="-1"> <mce:script type="text/javascript" src="js/jquery-1.3.2.min.js" mce_src="js/jquery-1.3.2.min.js"></mce:script> <mce:style type="text/css">
<!-- #header { margin-bottom: 1em; padding-bottom: 1em; border-bottom: 1px solid #eee; } .buttonListArea { float: left; width: 150px; padding-right: 10px; border-right: 1px solid #eee; margin-right: 10px; } .button{ cursor:pointer; } .buttonArea { margin: 10px; padding-bottom: 20px; } #load_content { float: left; width: 550px; text-align: center; } -->
</mce:style>
<style type="text/css" mce_bogus="1">
#header
{ margin-bottom: 1em; padding-bottom: 1em; border-bottom: 1px solid #eee; } .buttonListArea { float: left; width: 150px; padding-right: 10px; border-right: 1px solid #eee; margin-right: 10px; } .button{ cursor:pointer; } .buttonArea { margin: 10px; padding-bottom: 20px; } #load_content { float: left; width: 550px; text-align: center; } </style> </head> <body> <form id="form1" runat="server"> <div id="container"> <div id="header"> <h2>加载演示</h2> </div> <div class="buttonListArea"> <div class="buttonArea"> <div class="button" id="btnLoad1"> Load 1</div> </div> </div> <div id="load_content"> <h2>这是要被加载的区域</h2> </div> </div> </form> </body> </html>
Seven, JS modular management
Asynchronous loading, all js content needs to be a modular approach to segmentation organizations, there is a dependency, and asynchronous loading does not guarantee the order of execution.
In addition, namespace how management and other related issues. This part is beyond this article, refer to:
RequireJS , CommonJS and Wang Baoping (Taobao) of SeaJS its blog .
Eight, JS best practices:
- Minimize js file using compression tools to minimize it, and open http gzip compression. tool:
- Try not to put the <head>, as far as possible at the bottom of the page, the position is preferably </ body> before
- Avoid using document.write method
- Asynchronous loading js, use non-blocking, content is text
- Try not to use Inline Javascript directly on the page elements, such as onClick. Help unify the maintenance and caching.
reference:
- http://www.111cn.net/wy/js-ajax/46748.htm
- http://www.111cn.net/wy/js-ajax/46748_1.htm
- http://www.cnblogs.com/tiwlin/archive/2011/12/26/2302554.html
- Lazy Loading Asyncronous Javascript
-
In 2010 two lectures on Velocity China:Steve Souders(Google)的 Even Faster Web Sites (pdf)Li Mu (Taobao) the ad code stability and performance optimization of third-party real (pdf)
Reproduced in: https: //www.cnblogs.com/JoannaQ/archive/2013/06/04/3116373.html