[英]my script appending function doesn't work
我已經構建了這個函數來檢查是否已經在HTML中的head標簽上附加了腳本或樣式表。 如果腳本已存在,則該函數應防止再次附加相同的引用。
這是我的代碼:
function appendScript(path, type) {
var x = document.getElementsByTagName(type);
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == path || x[i].href == path){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
var head = document.getElementsByTagName('head')[0];
// We create the style
if (type == 'link') {
var style = document.createElement('link');
style.setAttribute("rel", "stylesheet");
style.setAttribute("type", "text/css");
style.setAttribute("href", path)
head.appendChild(style);
} else if (type == 'script') {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("src", path);
head.appendChild(script);
}
}
}
我把這個函數稱為這樣
appendScript('_css/style.test.css', 'link');
appendScript('_scripts/_js/script.test.js', 'script');
控制台日志中沒有任何問題。但問題是它不會阻止腳本再次附加。 任何人都可以發現錯誤嗎?
您使用相對路徑作為參數。 瀏覽器將其轉換為絕對路徑。 所以你要使用絕對路徑。 像那樣:
appendScript('http://stackoverflow.com/_scripts/_js/script.test.js', 'script');
我認為這是因為您使用相對URL。 如果檢查與“path”比較的元素的“src”屬性,它將包含協議和主機,因此它將不匹配。 你需要考慮這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.