js文件的装载和执行

1.浏览器对script引用的js文件分两步,下载,下载完毕后马上执行;这两步都会阻塞浏览器继续解析。

2.加入defer属性,<script defer type="text/javascript" src="some.js" ></script>,浏览器会异步加载js,待DOMContentLoaded后顺序执行js。

3.预加载js,自定义执行时机。

<script language="javascript" type="text/javascript">     function cachejs(script_filename){         var cache = document.createElement(\'object\');         cache.data = script_filename;         cache.id = "coolshell_script_cache_id";         cache.width = 0;         cache.height = 0;         document.body.appendChild(cache);     }       function loadjs(script_filename) {         var script = document.createElement(\'script\');         script.setAttribute(\'type\', \'text/javascript\');         script.setAttribute(\'src\', script_filename);         script.setAttribute(\'id\', \'coolshell_script_id\');           script_id = document.getElementById(\'coolshell_script_id\');         if(script_id){             document.getElementsByTagName(\'head\')[0].removeChild(script_id);         }         document.getElementsByTagName(\'head\')[0].appendChild(script);     }       function LoadJS(){         var script = \'./alert.js\';         loadjs(script);     }   </script>     ...   <p style="cursor: pointer" onclick="LoadJS()">Click to load alert.js </p>   ... ... <script>     cachejs(\'./alert.js\'); </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzyfjp.html