时间:2021-07-01 10:21:17 帮助过:3人阅读
Ajax.get("test.js", function (xhr) {
eval(xhr.responseText);
});
3。XHR注入
使用XHR获取脚本并创建script标签。
同样,通过XHR获取的脚本必须部署在和主页面相同的域中。
代码如下:
Ajax.get('test.js', function (xhr) {
injectscript(xhr.responseText);
});
function injectscript(scriptText) {
var s = document.createElement('script');
s.text = scriptText;
document.getElementsByTagName('head')[0].appendChild(s);
}
4。Script in Iframe
将需要的脚本放入到一个页面中,然后通过iframe来加载该页面。
缺点是iframe本身的开销比较大,另外浏览器安全机制不允许iframe中的js访问跨域的父页面,反之亦然。
5。Script DOM Element
JS动态创建script DOM元素并设置其src属性。
代码如下:
var scriptElem = document.createElement('script');
scriptElem.src = 'http://domain.com/test.js';
document.ge('head')[0].appendChild(scriptElem);
6。Script Defer
给script标签添加defer属性。
缺点是只有IE和一些新浏览器支持。
代码如下:
<script defer src='test.js'></script>
7。document.write Script Tag
使用document.write把HTML标签script写入页面。
缺点是只有在IE中是并行加载脚本的。
代码如下:
document.write("<script type='text/javascript' src='test.js'><\/script>");
有一个大家不曾广泛讨论的不同点是对于浏览器忙碌状态的影响,包括浏览器的状态栏、进度条、Tab图标以及鼠标。
当你加载多个彼此间有依赖关系的脚本时,还需要一种能够保证执行顺序的技术。
| 技术 
 | 并行下载 
 | 可以跨域 
 | 存在Script标签 
 | 忙碌指示 | 顺序保证 | 大小 (bytes) | 
| XHR Eval | IE, FF, Saf, Chr, Op | no | no | Saf, Chr | - | ~500 | 
| XHR Injection | IE, FF, Saf, Chr, Op | no | yes | Saf, Chr | - | ~500 | 
| Script in Iframe | IE, FF, Saf, Chr, Op | no | no | IE, FF, Saf, Chr | - | ~50 | 
| Script DOM Element | IE, FF, Saf, Chr, Op | yes | yes | FF, Saf, Chr | FF, Op | ~200 | 
| Script Defer | IE, Saf4, Chr2, FF3.1 | yes | yes | IE, FF, Saf, Chr, Op | IE, FF, Saf, Chr, Op | ~50 | 
| document.write Script Tag | IE, Saf4, Chr2, Op | yes | yes | IE, FF, Saf, Chr, Op | IE, FF, Saf, Chr, Op | ~100 |