Generally, third-party js is introduced directly. If the third-party is slow, it will block the rendering of the page. When the user is waiting, he will see a blank space. This user experience is not very good. Therefore, some js that do not need to be run immediately can be loaded asynchronously.
There are two loading methods, as follows
Add async=”async” in the script
async is a new attribute of html5, low version browsing The server is not compatible
<script type="text/javascript" async="async" src="http://thirdpart/js.js" ></script>
Use js method to load asynchronously
This method is to add script to the page after the listening page is loaded, so as to introduce the js file
(function() { function asyncLoad() { var src = "http://thirdpart/js.js"; var urls = src.split(","); var x = document.getElementsByTagName('body'); if(x && x[0]){ for (var i = 0; i < urls.length; i++) { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = urls[i]; x[0].appendChild(s); } } } window.attachEvent ? window.attachEvent('onload', asyncLoad) : window.addEventListener('load', asyncLoad, false); })();
The above is the detailed content of Asynchronous loading of js files in html pages. For more information, please follow other related articles on the PHP Chinese website!