码迷,mamicode.com
首页 > 编程语言 > 详细

Javascript 装载和执行

时间:2014-10-09 23:23:57      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   java   文件   sp   

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>

4.seajs和requirejs

seajs是执行到引用文件代码,再去引用下载,慢。

requirejs也是如此。

希望有什么选项能给个选择,指定哪些文件要预加载,哪些文件是需要时才去加载。

 

参考链接:

http://coolshell.cn/articles/9749.html

http://www.cnblogs.com/tiwlin/archive/2011/12/26/2302554.html

Javascript 装载和执行

标签:style   blog   http   color   io   ar   java   文件   sp   

原文地址:http://www.cnblogs.com/samwu/p/4014328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!