JS動態載入JS與CSS檔案

來源:互聯網
上載者:User

一 HTML頁面   jsforjscss.html

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <script type="text/javascript" src="loadjscssfile.js"></script> 6 <title>無標題文檔</title> 7 </head> 8 <body> 9 </body>10 </html>

二 動態載入js檔案的程式   loadjscssfile.js

// JavaScript Documentfunction loadjscssfile(filename,filetype){    if(filetype == "js"){        var fileref = document.createElement('script');        fileref.setAttribute("type","text/javascript");        fileref.setAttribute("src",filename);    }else if(filetype == "css"){            var fileref = document.createElement('link');        fileref.setAttribute("rel","stylesheet");        fileref.setAttribute("type","text/css");        fileref.setAttribute("href",filename);    }   if(typeof fileref != "undefined"){        document.getElementsByTagName("head")[0].appendChild(fileref);    }    }loadjscssfile("do.js","js");loadjscssfile("test.css","css");

三 被載入的 js檔案:do.js

alert("this is do");

四 被載入的 css檔案:test.css (css檔案中還可以用@import url("menu.css"); 引進其他css檔案)

@charset "utf-8";@import url("menu.css");@import url("../gundong.css");body{    background-color:gray;}

理論分析:

原理解析:第一步:使用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:

function loadjscssfile(filename, filetype){
if (filetype=="js"){ //判定檔案類型
var fileref=document.createElement('script')//建立標籤
fileref.setAttribute("type","text/javascript")//定義屬性type的值為text/javascript
fileref.setAttribute("src", filename)//檔案的地址
}
else if (filetype=="css"){ //判定檔案類型
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //開啟頁面時瀏覽器動態負載檔案
loadjscssfile("javascript.php", "js") // 開啟頁面時瀏覽器動態載入"javascript.php" ,
loadjscssfile("mystyle.css", "css") //開啟頁面時瀏覽器動態載入.css 檔案

接下來的工作是綁定到<head>標籤。綁定的時候有一個問題就是同一個檔案有可能被我們綁定兩次,綁定兩次瀏覽器也不會出現異常,但是效率就低了。為了避免r

這種情況我們可以新增一個全域陣列變數,把綁定的檔案名稱字儲存在裡面,每次綁定前先檢查一下是否已經存在,假如存在就提示已經存在,假如不存在就綁定。r

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:

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.

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.