2013-04-13 44 views
11

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

但我想要一种方法来查看脚本或样式表是否已被追加,然后再追加它。追加一个已经存在的脚本或样式表将是愚蠢的。

问:如何使用javascript检查是否在头标记中存在脚本,如果不是,那么追加元素?

编辑

我已经根据从@KernelPanik答案的功能。它还没有工作,但希望它会。该功能目前存在疑问:my script appending function doesn't work

+3

你可以在你的脚本/样式/链接标记上加一个id并检查它是否存在。 – Vatev

+0

@Vatev唯一的问题是,它只支持一些浏览器 – Dimser

+1

如何? document.scripts或document.getElementsByTagName(“脚本”)及其属性是所有浏览器都支持的afaik – mplungjan

回答

0

也许headjs可以帮到你。

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

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

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

问题不是添加脚本..它是检测它的存在,然后添加脚本如果它们不存在。 – Dimser

+0

like js.onload = function(){alert('loaded');} – Fakefish

3

可以使用DOM getElementsByTagName("script")把所有的<script>标签在文档中。然后,您可以检查返回的每个脚本标记的src网址,以获取已添加到头部部分的脚本的URL。同样,你可以通过用“style”替换“script”的搜索来为样式表做类似的事情。

例如,如果附加到<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 
} 

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

10

如果你可以使用jquery,th是的代码是好的

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

不需要使用HTML5的“text/javascript”属性 – Serge

+0

可爱!如果开发者需要添加jQuery本身呢?香草不会在这里最佳的解决方案? –

-3

您可以尝试调用一些功能,对象,从可变JS脚本文件,如果它发现它,然后它的存在,如果没有,你需要插入该js脚本文件。

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-shim如果您在不支持ES5的浏览器(IE7和IE8 ...)

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; 
} 
1

我用杰克·李的解决方案。这很容易实现,并快速versitile几乎任何类型的文件....我没有扩大任何事情......我其实可能愣了一下......只是想列出我做了什么,如果它帮助某人否则...

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...