Javascript 仅当不';不存在

Javascript 仅当不';不存在,javascript,append,Javascript,Append,我想在加载特定的div时向我的站点添加其他脚本和样式。 我首先定义脚本或样式表的路径,然后创建一个元素。此后,我将在HTML中将元素附加到head标记 但是,在我再次追加之前,我想知道脚本或样式表是否已经被追加了。附加一个已经存在的脚本或样式表是愚蠢的 问:如何使用javascript检查head标记中是否已经存在脚本,如果不存在,如何追加元素 编辑 我根据@KernelPanik的答案制作了一个函数。它还不起作用,但希望能起作用。该功能目前存在疑问:也许可以帮助您 或者,您可以在脚本标记中添加

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

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

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

编辑

我根据@KernelPanik的答案制作了一个函数。它还不起作用,但希望能起作用。该功能目前存在疑问:

也许可以帮助您

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

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

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

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

例如,如果附加到
部分的脚本的url是
标题\u url.html

var x=document.getElementsByTagName(“脚本”);
var标头已添加=false;
对于(变量i=0;i
同样,如果附加到
部分的样式的url是
标题\u style.css

var x=document.getElementsByTagName(“样式”);
var标头已添加=false;
对于(变量i=0;i

这里还提出了一个类似的问题:

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

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

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

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

它使用函数。如果您的浏览器不支持ES5(IE7和IE8…),您可能需要一个。它很容易实现,并且可以快速地对任何类型的文件进行版本化。。。。我没有扩展任何内容…实际上我可能有点让它发呆了。。。我只是想列出我所做的,以防对其他人有所帮助

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... 
var libu jq='//pathtofile/jquery.js';
var lib_bs='//pathtofile/bootstrap.min.3.5.js';
var libu cs='//pathtofile.css';
///检查具有SRC属性的文件
函数isLoadedScript(lib){
return document.querySelectorAll('[src=“'+lib+''“]])。长度>0
}
///使用HREF属性检查文件
函数isLoadedCss(lib){
return document.querySelectorAll('[href=“'+lib+'“]]”)。长度>0
}
///加载script.js文件
函数加载脚本(链接){
文件。写(“”);
}
///加载style.css文件
函数加载CSS(链接){
文件。写(“”);
}
///运行功能;如果没有列出任何文件,那么它将运行函数来获取列出的URL///为每个要检查的文件单独运行一个。
如果(!isLoadedScript(lib_jq)){loadScript(lib_jq);}
如果(!isLoadedScript(lib_bs)){loadScript(lib_bs);}
如果(!isLoadedCss(lib_cs)){loadCss(lib_cs);}
我知道总有一个“更好”和更“优雅”的解决方案,但对我们初学者来说,我们必须在开始理解它之前让它工作起来。。。

您可以在脚本/style/link标记上添加一个id,并检查它是否存在。@Vatev唯一的问题是,它只受某些浏览器的支持。为什么?document.scripts或document.getElementsByTagName(“脚本”)及其属性完全受所有浏览器支持
getElementById
适用于任何标记,创建时只需设置id即可。问题不在于添加脚本。。这是为了检测它的存在,然后在脚本不存在时追加脚本。比如js.onload=function(){alert('loaded');}在HTML5中不再需要“text/javascript”属性!如果开发人员需要添加jQuery本身呢?香草javascript不是这里的最佳解决方案吗?我喜欢这个答案,但没有在Chrome上使用它,因为Chrome预先添加了
”http://localhost/“
如果使用了相对路径,例如
test.js
。我现在使用
x[I].getAttribute('src')
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...