国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > CSS > 正文

動態加載外部CSS與JS文件

2024-07-11 08:24:57
字體:
來源:轉載
供稿:網友

  動態加載外部CSS與JS文件使用dom創建<script>或者<link>標簽,并給他們附加屬性,如type等。然后使用appendChild方法把標簽綁定到另一個標簽,一般是綁到<head>。
  應用:
  1、提高代碼的復用,減少代碼量;
  2、添加一個javascript控制器和 session可以實現動態改變頁面樣式;
  3、由于是頁面是從上到下依次加載文件的,并且邊加載邊解釋,所以可以添加javascript控制器控制頁面文件的加載順序,如先加載css布局文件,再顯示有圖片的css美化文件,之后再加載大的falsh文件,或者安內容的重要性來加載。
  To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "script" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:

  接下來的工作是綁定到<head>標簽。綁定的時候有一個問題就是同一個文件有可能被我們綁定兩次,綁定兩次瀏覽器也不會出現異常,但是效率就低了。為了避免
  這種情況我們可以新增一個全局數組變量,把綁定的文件名字保存在里面,每次綁定前先檢查一下是否已經存在,如果存在就提示已經存在,如果不存在就綁定。
document.getElementsByTagName("head")[0].appendChild(fileref)
  By referencing the HEAD element of the page first and then calling appendChild(), this means the newly created element is added to the very end of the HEAD tag. Furthermore, you should be aware that no existing element is harmed in the adding of the new element- that is to say, if you call loadjscssfile("myscript.js", "js") twice, you now end up with two new "script" elements both pointing to the same Javascript file. This is problematic only from an efficiency standpoint, as you'll be adding redundant elements to the page and using unnecessary browser memory in the process. A simple way to prevent the same file from being added more than once is to keep track of the files added by loadjscssfile(), and only load a file if it's new:
var filesadded="" //保存已經綁定文件名字的數組變量
function checkloadjscssfile(filename, filetype){
if (filesadded.indexOf("[" filename "]")==-1){// indexOf判斷數組里是否有某一項
loadjscssfile(filename, filetype)
filesadded ="[" filename "]" //把文件名字添加到filesadded
}
else
alert("file already added!")//如果已經存在就提示
}
checkloadjscssfile("myscript.js", "js") //success
checkloadjscssfile("myscript.js", "js") //redundant file, so file not added
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 红桥区| 喀什市| 昌吉市| 邛崃市| 鄢陵县| 江山市| 正蓝旗| 台南县| 浠水县| 富民县| 太原市| 凉城县| 长寿区| 盈江县| 大化| 萝北县| 昌宁县| 高州市| 米脂县| 武冈市| 嵊泗县| 嘉鱼县| 密山市| 东方市| 吴川市| 南充市| 晋宁县| 罗江县| 恩平市| 扬州市| 三台县| 武鸣县| 大足县| 开封市| 十堰市| 唐河县| 凌海市| 百色市| 德清县| 阳朔县| 哈巴河县|