我的脚本追加函数不起作用

my script appending function doesn't work

本文关键字:不起作用 函数 追加 脚本 我的      更新时间:2023-09-26

我已经构建了这个函数来检查是否已经将脚本或样式表添加到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');

控制台日志中没有任何错误。但问题是,它并不能阻止脚本再次被追加。有人能看出这个错误吗?

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

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

我认为这是因为你使用了相对url。如果您检查与"path"比较的元素的"src"属性,它将包含协议和主机,因此它不会匹配。