my script appending function doesn't work

2019-06-07 07:02发布

问题:

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.

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?

回答1:

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


回答2:

I think it's because you use relative URLs. 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. You need to consider that.