我的脚本附加功能不起作用 [英] my script appending function doesn't work
本文介绍了我的脚本附加功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我构建了这个函数来检查脚本或样式表是否已经附加到 HTML 中的 head 标签.如果脚本已经存在,函数应该防止再次附加相同的引用.
I have builded this function to check wether or not a script or stylesheet already has been appended to the head tag in HTML. If the script already exists the function should prevent appending the same reference again.
这是我的代码:
function appendScript(path, type) {
var x = document.getElementsByTagName(type);
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == path || x[i].href == path){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
var head = document.getElementsByTagName('head')[0];
// We create the style
if (type == 'link') {
var style = document.createElement('link');
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", path)
head.appendChild(style);
} else if (type == 'script') {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("src", path);
head.appendChild(script);
}
}
}
我这样调用函数
appendScript('_css/style.test.css', 'link');
appendScript('_scripts/_js/script.test.js', 'script');
控制台日志中没有任何问题.. 但问题是它不会阻止脚本再次被附加.有人能发现错误吗?
There is nothing wrong in the console log.. But the thing is that it doesn't prevent the scripts from being appended again. Can anybody spot the mistake?
推荐答案
您正在使用相对路径作为参数.浏览器将其转换为绝对路径.所以你必须使用绝对路径.像这样:
You're using relative path as parameter. Browser converts it to absolute path. So you've to use absolute path. Like that:
appendScript('http://stackoverflow.com/_scripts/_js/script.test.js', 'script');
这篇关于我的脚本附加功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文