动态script标签加载js文件需要注意的问题

对于下面一段js代码

<?php
var excuteScript = function (id, scriptSource, charset
) {
var
head = document.getElementsByTagName(‘head’)[0
];
var
oldScript = document.getElementById(id
);
if (
oldScript
) {
head.removeChild(oldScript
);
}
var
newScript = document.createElement(‘script’
);
if (
charset
) {
newScript.charset = charset
;
} else {
newScript.charset = ‘gb2312’
;
}
newScript.id = id
;
newScript.type = ‘text/javascript’
;
scriptSource += (/?/.test(scriptSource)?"&":"?") + "_=" + (new Date()).getTime
();
newScript.src = scriptSource
;
head.appendChild(newScript
);
};
?>

对于IE和firefox是有所不同的:
IE: 请求发起在给script标签的src属性赋值的时候,至少ie8是这样
Firefox: 请求发起于appendChild的时候,如果创建的标签没有append操作,将不会发起请求; 至少firefox 3.0.11 是这样

我们可以通过下面的脚本测试一下:

<html>
<
head><title>test script </title></head>
<
body>
<
script>
scriptSource = "http://phpor.net/404.js";
var
head = document.getElementsByTagName(‘head’)[0];
var
oldScript = document.getElementById(id);
if (
oldScript) {
head.removeChild(oldScript);
}
var
newScript = document.createElement(‘script’);
newScript.charset = ‘gb2312’;
newScript.id = "testid";
newScript.type = ‘text/javascript’;

newScript.src = scriptSource;
newScript.src = scriptSource +"?2";
//head.appendChild(newScript);

</script>
</body>
</html>

http://phpor.net/samples/html/test_script.html

留下评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据