日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

js 判断js,css是否引入,确保不重复引入

發布時間:2023/11/27 生活经验 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 js 判断js,css是否引入,确保不重复引入 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

js?判斷js,css是否引入,確保不重復引入

?(2009-10-31 21:33:44) 轉載
標簽:?

雜談

?
分類:?js
基本原理:
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
??var fileref=document.createElement_x('script')
??fileref.setAttribute("type","text/javascript")
??fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
??var fileref=document.createElement_x("link")
??fileref.setAttribute("rel", "stylesheet")
??fileref.setAttribute("type", "text/css")
??fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
??document.getElementsByTagName_r("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") dynamically load and add this .css file

注意點:
默認掛在dom的第一個節點下,要保證不影響原有的頁面的邏輯。
防止重復加載。
var filesadded="" //list of files already added

function checkloadjscssfile(filename, filetype){
if (filesadded.indexOf("["+filename+"]")==-1){
??loadjscssfile(filename, filetype)
??filesadded+="["+filename+"]" //List of files added in the form "[filename1],[filename2],etc"
}
else
??alert("file already added!")
}

checkloadjscssfile("myscript.js", "js") //success
checkloadjscssfile("myscript.js", "js") //redundant file, so file not added



我自己寫的例子如下:
isexist這個變量要定義在需要引入的js里,用typeof去檢測改變量是否存在?如果等于undefined,說明不存在,那就引入外部js,否則,就不引入!
????if(typeof(isexist) == 'undefined')
????{
????????var fileref = document.createElement_x('script');
????????fileref.setAttribute("type","text/javascript");
?????????fileref.setAttribute("src","<?php echo $html->url('/')?>js/valide.js");
????????document.getElementsByTagName_r("head")[0].appendChild(fileref);
????????
????}

轉載于:https://www.cnblogs.com/lxg0/articles/5541908.html

總結

以上是生活随笔為你收集整理的js 判断js,css是否引入,确保不重复引入的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。