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

首頁 > 開發 > CSS > 正文

動態加載外部css或js文件

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

原理解析:第一步:使用dom創建<script>或者<link>標簽,并給他們附加屬性,如type等第二步:使用appendchild方法把標簽綁定到另一個標簽,一般是綁到<head>.

應用:1、提高代碼的復用,減少代碼量;2、添加一個javascript控制器和 session可以實現動態改變頁面樣式;3、由于是頁面是從上到下依次加載文件的,并且邊加載邊解釋,所以可以添加javascript控制器控制頁面文件的加載順序,如先加載css布局文件,再顯示有圖片的css美化文件,之后再加載大的falsh文件,或者安內容的重要性來加載。/r

閱讀提示:e文不好的初學者可以直接看中文,然后拷貝代碼試驗下。/r

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>標簽。綁定的時候有一個問題就是同一個文件有可能被我們綁定兩次,綁定兩次瀏覽器也不會出現異常,但是效率就低了。為了避免/r

這種情況我們可以新增一個全局數組變量,把綁定的文件名字保存在里面,每次綁定前先檢查一下是否已經存在,如果存在就提示已經存在,如果不存在就綁定。/r

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:

here i'm just crudely detecting to see if a file that's set to be added already exists within a list of added files' names stored in variable filesadded before deciding whether to proceed or not.
ok, moving on, sometimes the situation may require that you actually remove or replace an added .js or .css file. lets see how that's done next.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 额尔古纳市| 巧家县| 綦江县| 治县。| 双流县| 洪江市| 察哈| 锡林浩特市| 留坝县| 崇阳县| 崇礼县| 来安县| 湖南省| 桦甸市| 小金县| 广灵县| 思茅市| 阜新| 定西市| 金昌市| 南郑县| 如皋市| 格尔木市| 凤凰县| 湾仔区| 杨浦区| 邵阳县| 五家渠市| 分宜县| 安仁县| 静宁县| 建湖县| 普兰店市| 科技| 定边县| 黑山县| 加查县| 吉安县| 海南省| 阿克苏市| 苗栗县|