关于IE动态加载script的几个注意点

用js动态链接一个外部的js文件,很简单:

var script = document.createElement (“script”);
script.src = “XXX.js”;
document.getElementsByTagName(“head”).item(0).appendChild (script);

但是一个注意的地方是,其实在IE下,执行到script.src = “XXX.js”;这一句代码时,IE已经去加载script代码了,但是不会执行链入的js代码,必须等到插入到document中后,才会执行,而在标准浏览器下,则是在执行插入到document中的代码时才会去加载外部js文件。所以需要注意的是,但你使用了jQuery等第三方js库进行插入的时候尤其要注意,这会导致IE下有两次请求。

本人在IE6,IE9,IE10下亲测IE存在这个问题。

这个网友还对在script标签中设置了src属性,但是script标签对内有内容时浏览器如何处理的问题进行了研究,并通过查找了相关标准给出了答案。

HTML4标准

If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element’s contents and retrieve the script via the URI

文中还提到HTML5标准对动态修改已经存在的script标签的src属性时浏览器应如何处理

Changing the src, type, charset, async, and defer attributes dynamically has no direct effect; these attribute are only used at specific times described below.

文中指的网友文章地址 http://www.w3ctech.com/p/1141,具体内容大家还是看这位网友的原文。