欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

让JavaScript和其它资源并发下载的方法

时间:2021-03-23 09:35:10|栏目:JavaScript代码|点击:

在IE6/7里JavaScript会从两个方面阻碍页面呈现:
script标签下面的网页资源在script加载完之前会停止请求、下载。
script标签下面的html元素在script加载完之前会停止渲染。

在ie6/7 firefox2/3 Safari3 Chrome1 和 opera下 script标签会阻碍下载:

虽然在ie8,safari4,chrome2下script可以并发,但依然阻碍了其他资源的下载:

有6种方法可以使script与其他资源并行下载:

1.XHR eval ― 通过XHR(XMLHttpRequest 对象)下载script,然后用eval方法执行XHR的responseText
2.XHR Injection ― 通过XHR下载script,然后建立一个script标签并把它插入文档中(body或者head标签内),接着把script标签的text属性设置为XHR的responseText的值
3.XHR in Iframe ― 把script标签放到一个iframe里,通过iframe下载它
4.Script DOM Element ― 创建script标签并把它的src属性指向你的脚本地址
5.Script Defer ― 添加script标签的defer属性,这个只在ie中有效,但firefox3.1也支持这个属性了
6.使用document.write方法在页面中写入<script src="">,这个只在ie里有效

可以通过Cuzillion查 看各个方法的使用例子。

如果有一些内联脚本需要在外部脚本执行后才能执行,那就需要同步(synchronize)他们了。称作”coupling”,Coupling Asynchronous Scripts 这篇文章介绍了一些目前可以实现“coupling”的方法。

headjs,能使JS并发下载(但是顺序执行):http://headjs.com/

复制代码 代码如下:

head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() { 
  // all done 
}); 
  
// the most simple case. load and execute single script without blocking. 
head.js("/path/to/file.js"); 
  
// load a script and execute a function after it has been loaded 
head.js("/path/to/file.js", function() { 
  
}); 
  
// load files in parallel but execute them in sequence 
head.js("file1.js", "file2.js", ... "fileN.js"); 
  
// execute function after all scripts have been loaded 
head.js("file1.js", "file2.js", function() { 
  
}); 
  
// files are loaded in parallel and executed in order they arrive 
head.js("file1.js"); 
head.js("file2.js"); 
head.js("file3.js"); 
  
// the previous can also be written as 
head.js("file1.js").js("file1.js").js("file3.js");

上一篇:javascript禁用Tab键脚本实例

栏    目:JavaScript代码

下一篇:鼠标经过导航菜单时颜色改变效果

本文标题:让JavaScript和其它资源并发下载的方法

本文地址:http://www.codeinn.net/misctech/86432.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有