简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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