简体   繁体   English

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

[英]my script appending function doesn't work

I have builded this function to check wether or not a script or stylesheet already has been appended to the head tag in HTML. 我已经构建了这个函数来检查是否已经在HTML中的head标签上附加了脚本或样式表。 If the script already exists the function should prevent appending the same reference again. 如果脚本已存在,则该函数应防止再次附加相同的引用。

This is my code: 这是我的代码:

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

        }
    }
}

And I call the function like this 我把这个函数称为这样

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

I think it's because you use relative URLs. 我认为这是因为您使用相对URL。 If you check the "src" attribute of the elements you compare to "path", it will contain the protocol and host, so it won't match. 如果检查与“path”比较的元素的“src”属性,它将包含协议和主机,因此它将不匹配。 You need to consider that. 你需要考虑这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM