2014-03-13 47 views
0

僅使用JS我需要一種方法來查看在添加某些東西前是否已將具有給定源的腳本添加到dom中以避免衝突。JS檢查是否添加了給定源的腳本

即我想檢查是否有任何腳本標記已添加與'somedomain'在src中。如果有做X,如果不做Ÿ

<script src="http://www.somedomain.com/ascript.js"></script> 
+0

好,然後通過現有的'script'元素循環,看看他們的'src'屬性... – CBroe

回答

0
var scripts = document.getElementsByTagName("script"); // get all the script elements 

var anyHasDomain = false, // no one has the domain yet 
    domain = "http://www.somedomain.com/ascript.js"; // the domain to look for 

for(var i = 0;i < scripts.length; i++){ 
    if(scripts[i].src === domain) // if any has domain 
     anyHasDomain = true; // set true 
} 

if(anyHasDomain) alert("y"); // do x 
else alert("n"); // do y 

Demo

希望幫助!

1
var tags = document.getElementsByTagName('script'); 

function hasDomain(tags, somedomain) { 
    var found = false; 
    var regex = new RegExp(somedomain, 'gi'); 
    for (var i = 0, l = tags.length; i < l; i++) { 
    if (regex.test(tags[i].src) === true) { 
     found = true; 
     break; 
    } 
    } 
    return found; 
} 

hasDomain(tags, 'www.somedomain.com'); // true 

Fiddle