我的脚本追加功能不起作用

时间:2013-04-13 13:14:02

标签: javascript function append

我已经构建了这个函数来检查是否已经将脚本或样式表附加到HTML中的head标记。如果脚本已经存在,则该函数应该阻止再次附加相同的引用。

这是我的代码:

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');

控制台日志中没有任何问题。但问题是它不会阻止脚本再次附加。任何人都可以发现错误吗?

2 个答案:

答案 0 :(得分:3)

您使用相对路径作为参数。浏览器将其转换为绝对路径。所以你要使用绝对路径。像那样:

appendScript('http://stackoverflow.com/_scripts/_js/script.test.js', 'script');

答案 1 :(得分:0)

我认为这是因为您使用相对网址。如果检查与“path”比较的元素的“src”属性,它将包含协议和主机,因此它将不匹配。你需要考虑这一点。

相关问题