2012-05-02 83 views
4
<head> 
    <link rel="stylesheet" type="text/css" href="mystyle.css"> 
    <script src="myscript.js"></script> 
</head> 

我想如果有一個資源包括在頭如何檢查是否一個CSS/JS資源包括在頭

checkIfHeaderHas('myscript.js'); // would return true 
checkIfHeaderHas('mystyle.css'); // would return true 
checkIfHeaderHas('mybla.css'); // would return false 

,檢查功能,但我不知道如何我可以去尋找頭文件名? (在'src'中,如果它是javascript,或者在'href'中,如果它是一個css)

+1

所以,你只是想知道他們是否已被*包括*在頁面中,或者他們是否滿載?因爲這是兩個非常不同的問題。 –

+1

對於js,您可以在.js文件中定義一個變量(或常量),並檢查它是否在頁面中定義。 – Aziz

+0

@ Xeon06,包含在頁面 – foreyez

回答

4

在jquery中使用.length會爲此工作。 (未測試!)

只是檢查,看是否有元素設置爲你的CSS文件的URL href屬性存在:

if (!$("link[href='/path/to.css']").length){ 
alert('not loaded'); 
}else{ 
alert('loaded!'); 
} 
+0

簡短,甜美並且重要。 – foreyez

4

我做了一個小功能,你想要做什麼。它遍歷所有<link><script>元素,直到找到具有該名稱的腳本。如果不是,則返回false。

function checkIfIncluded(file) { 
    var links = document.getElementsByTagName("link"); 
    for(var i = 0; i < links.length; i++) { 
     if (links[i].href.substr(-file.length) == file) 
      return true; 
    } 

    var scripts = document.getElementsByTagName("script"); 
    for(var i = 0; i < scripts.length; i++) { 
     if (scripts[i].src.substr(-file.length) == file) 
      return true; 
    } 

    return false; 
} 

console.log(checkIfIncluded("mystyle.css")); 
console.log(checkIfIncluded("myscript.js")); 
console.log(checkIfIncluded("mybla.css")); 
​ 

Live example

注意,這不僅會尋找資源在<head>,但thew整個文件內。如果你真的需要查看頭部內部,告訴我,我們會找出其他的東西。

+0

這個工程也很棒,但是遍歷並不像我選擇的解決方案那麼優雅 – foreyez

+0

確實是哥們。 –

+0

不錯,它有不依賴於jQuery的好處 – liljoshu

6

如果你使用jQuery,你也許可以這樣做:

var checkIfHeaderHas = function(fileName) { 

    // Start with CSS. 
    $.each($("header link"), function() { 
     if ($(this).attr("href").toLowerCase() === fileName.toLowerCase()) 
      return true; 
    }); 

    // Then JavaScript. 
    $.each($("header script"), function() { 
     if ($(this).attr("src").toLowerCase() === fileName.toLowerCase()) 
      return true; 
    }); 

    // Default response. 
    return false; 
} 

道歉什麼,這不是完全正確。我從手機裏拿出來,沒有時間去測試。

+0

如果我需要檢查'jquery'文件本身,以及它是否已經加載,那麼在這一點上不會失敗。因爲'$'不會被識別 –

相關問題