2013-04-13 65 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...