如果不存在,只添加脚本到头部

时间:2013-04-13 12:14:19

标签: javascript append

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

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

问:如何使用javascript检查head标签中是否已存在脚本,如果没有,则附加该元素?

修改

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

7 个答案:

答案 0 :(得分:12)

如果你可以使用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');

答案 1 :(得分:3)

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

例如,如果附加到<head>部分的脚本的网址为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
}

同样,如果附加到<head>部分的样式的网址为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

答案 2 :(得分:3)

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 :(得分:2)

我使用了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... 

答案 4 :(得分:1)

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

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

答案 5 :(得分:0)

也许headjs可以帮到你。

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

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

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

答案 6 :(得分:-3)

您可以尝试从该js脚本文件中调用某个函数,对象,变量,如果找到它然后它存在,如果不存在,则需要插入该js脚本文件。