仅使用JS我需要一种方法来查看在添加内容之前是否已将具有给定源的脚本添加到dom中以避免冲突。
即我想查看是否添加了任何脚本标记' somedomain'在src。如果有做x,如果不做y
<script src="http://www.somedomain.com/ascript.js"></script>
答案 0 :(得分: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
答案 1 :(得分: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
希望有所帮助!