我的脚本附加功能不起作用 [英] my script appending function doesn't work

查看:65
本文介绍了我的脚本附加功能不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了此功能来检查是否在HTML中的head标签上附加了脚本或样式表.如果脚本已经存在,则该函数应避免再次添加相同的引用.

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.

这是我的代码:

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

控制台日志中没有任何错误..但事实是,这不会阻止脚本再次被附加.有人可以发现错误吗?

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

这篇关于我的脚本附加功能不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆