my script appending function doesn't work

雨燕双飞 提交于 2020-01-03 03:15:10

问题


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.



来源:https://stackoverflow.com/questions/15988186/my-script-appending-function-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!