【问题标题】:only add script to head if doesn't exist仅在不存在时将脚本添加到头部
【发布时间】:2013-04-05 22:38:35
【问题描述】:

我想在加载特定 div 时向我的网站添加其他脚本和样式。 我首先定义脚本或样式表的路径,然后创建一个元素。此后,我将元素附加到 HTML 中的 head 标签。

但我想在再次追加之前查看脚本或样式表是否已经追加。附加一个已经存在的脚本或样式表是愚蠢的。

问:如何使用javascript检查head标签中是否已经存在脚本,如果不存在则追加元素?

编辑

我根据@KernelPanik 的回答制作了一个函数。它还没有工作,但希望它会。该功能目前有问题:my script appending function doesn't work

【问题讨论】:

  • 你可以在你的 script/style/link 标签上放一个 id 并检查它是否存在。
  • @Vatev 唯一的问题是只有部分浏览器支持
  • 怎么样?所有浏览器都支持 document.scripts 或 document.getElementsByTagName("script") 及其属性
  • getElementById 适用于任何标签,您只需要在创建时设置 id。

标签: javascript append


【解决方案1】:

如果你会用jquery,这段代码就不错了

function appendScript(filepath) {
    if ($('head script[src="' + filepath + '"]').length > 0)
        return;

    var ele = document.createElement('script');
    ele.setAttribute("type", "text/javascript");
    ele.setAttribute("src", filepath);
    $('head').append(ele);
}

function appendStyle(filepath) {
    if ($('head link[href="' + filepath + '"]').length > 0)
        return;

    var ele = document.createElement('link');
    ele.setAttribute("type", "text/css");
    ele.setAttribute("rel", "Stylesheet");
    ele.setAttribute("href", filepath);
    $('head').append(ele);
}

在你的代码中写

appendScript('/Scripts/myScript.js');
appendStyle('/Content/myStyle.css');

【讨论】:

  • HTML5 不再需要“text/javascript”属性
  • 可爱!如果开发者需要自己添加 jQuery 怎么办?这里不是香草javascript最佳解决方案吗?
【解决方案2】:
var lib = '/public/js/lib.js';

if (!isLoadedScript(lib)) {
  loadScript(lib);
}

// Detect if library loaded
function isLoadedScript(lib) {
  return document.querySelectorAll('[src="' + lib + '"]').length > 0
}

// Load library
function loadScript(lib) {
  var script = document.createElement('script');
  script.setAttribute('src', lib);
  document.getElementsByTagName('head')[0].appendChild(script);
  return script;
}

【讨论】:

    【解决方案3】:

    您可以使用 DOM getElementsByTagName("script") 来获取文档中的所有 <script> 标记。然后,您可以检查返回的每个脚本标记的 src url,以获取已添加到 head 部分的脚本的 url。同样,您可以通过将“script”的搜索替换为“style”来对样式表执行类似的操作。

    例如,如果附加到<head> 部分的脚本的url 是header_url.html

    var x = document.getElementsByTagName("script");
    var header_already_added = false;
    
    for (var i=0; i< x.length; i++){
        if (x[i].src == "header_url.html"){
            // ... do not add header again
            header_already_added = true;
        }
    }
    
    if (header_already_added == false){
        // add header if not already added
    }
    

    同样,如果附加到&lt;head&gt;部分的样式的url是header_style.css

    var x = document.getElementsByTagName("style");
    var header_already_added = false;
    
    for (var i=0; i< x.length; i++){
        if (x[i].src == "header_style.css"){
            // ... do not add header again
            header_already_added = true;
        }
    }
    
    if (header_already_added == false){
        // add header if not already added
    }
    

    这里也有人问过类似的问题:Check if Javascript script exists on page

    【讨论】:

    • 我喜欢这个答案,但未能将它与 Chrome 一起使用,因为 Chrome 会在使用相对路径的情况下添加 "http://localhost/",例如test.js。我现在使用x[i].getAttribute('src')
    【解决方案4】:

    我使用了 Jack Lee 的解决方案。它很容易实现并且几乎可以使用任何类型的文件快速通用......我没有扩展任何东西......我实际上可能有点惊呆了......只是想列出我所做的事情以防它帮助某人否则……

    var lib_jq = '//pathtofile/jquery.js';
    var lib_bs = '//pathtofile/bootstrap.min.3.5.js';
    var lib_cs = '//pathtofile.css';
    
     ///checks files with the SRC attribute
    function isLoadedScript(lib) {
        return document.querySelectorAll('[src="' + lib + '"]').length > 0
    }
    ///checks files with the HREF attribute
    function isLoadedCss(lib) {
        return document.querySelectorAll('[href="' + lib + '"]').length > 0
    }
    ///loads the script.js files
    function loadScript(link) {
       document.write('<scr' + 'ipt type="text/javascript" src="'+link+'"></scr' + 'ipt>');
    }
    
    ///loads the style.css files
    function loadCss(link) {
       document.write('<link rel="stylesheet" href="'+link+'">');
    }
    
     /// run funtion; if no file is listed, then it runs the function to grab the URL listed. ///Run a seperate one for each file you wish to check. 
    if (!isLoadedScript(lib_jq)) { loadScript(lib_jq); }
    if (!isLoadedScript(lib_bs)) { loadScript(lib_bs); }
    if (!isLoadedCss(lib_cs))    { loadCss(lib_cs);    }
    
    I know there is always a "better" and more "elegant" solution, but for us beginiers, we got to get it working before we can start to understand it... 
    

    【讨论】:

      【解决方案5】:

      另一种使用下面的函数助手的方法

      function isScriptAlreadyPresent(url) {
        var scripts = Array.prototype.slice.call(document.scripts);
        return scripts.some(function(el) {
           return el.src && el.src != undefined && el.src == url;
        });
      }
      
      isScriptAlreadyPresent('http://your_script_url.tld/your_lib.js');
      

      它使用Array.prototype.some 函数。如果您使用的浏览器不支持 ES5(IE7 和 IE8...),您可能需要 es5-shim

      【讨论】:

        【解决方案6】:

        也许headjs可以帮助你。

        或者您可以在脚本标签中添加 onload 属性。

        我的英语有点差,所以我可能误解了你的问题。

        if(ie){
          js.onreadystatechange = function(){
            if(js.readyState == 'complete'){
              callback(js);
          }
        }
        else{  
        js.onload = function(){
          callback(js);
        }
        

        【讨论】:

        • 问题不在于添加脚本.. 它是检测它的存在,然后如果它们不存在则附加脚本。
        • like js.onload=function(){alert('loaded');}
        【解决方案7】:

        你可以尝试从那个js脚本文件中调用一些函数、对象、变量,如果找到它就存在,如果没有,你需要插入那个js脚本文件。

        【讨论】:

          猜你喜欢
          • 2014-01-30
          • 2015-09-26
          • 2015-06-30
          • 2023-01-04
          • 1970-01-01
          • 1970-01-01
          • 2013-04-15
          • 2022-06-11
          • 2015-12-23
          相关资源
          最近更新 更多