js優化提高訪問速度

1、給JS文件減肥。javascript

有的人爲了給網站增長炫目效果,每每會使用一些JS效果代碼,這在上個世紀彷佛還很流行,對於如今來講,最好在用戶體驗確實須要的狀況下,使用這些東西。至於但願給本身的JS文件減肥的童鞋,網上的工具裏有不少,在百度一搜就會有應用,功能很全。把一個已經完善的JS文件進行壓縮是主流網站的一個慣性動做,由於壓縮量確實很可觀。如下是幾個比較好的壓縮工具:php

YUI壓縮工具 (http://developer.yahoo.com/yui/compressor/)
Dean Edwards Packer (http://dean.edwards.name/packer/)
JSMin (http://crockford.com/JavaScript/jsmin)css

2、儘可能減小DOM訪問html

使用JavaScript訪問DOM元素很容易,代碼更容易閱讀,可是速度很慢。下面介紹幾個要點:限制使用JavaScript來修飾網頁佈局,把針對訪問元素的引用緩存起來。有時,當你的網站依賴大量的DOM改動時,就應該考慮限制你的標記。這是改用HTML五、捨棄那些原來的XHTML和HTML4的一個充分理由。前端

3、使用適當的CDNjava

如今許多網頁使用內容分發網絡(CDN)。它能夠改進你的緩存機制,由於每一個人均可以使用它。它還能爲你節省一些帶寬。你很容易使用ping檢測或使用Firebug調試那些服務器,以便搞清能夠從哪些方面加快數據的速度。選擇CDN時,要照顧到你網站那些訪客的位置。記得儘量使用公共存儲庫。shell

4、把不着急用的JS文件放到頁面的底部數組

當更多地考慮用戶對網站的速度體驗時,在頁面底部裝入JS文件是一個很是好的作法。易用性和用戶放在首位,JavaScript放在末位。對於追求技術的不少前端人員來講,這彷佛很難接受,但也應該有所準備,有些用戶會禁用JavaScript。瀏覽器

5、在頭部以異步方式裝入JS緩存

爲了統計網站的各類信息,咱們一般會藉助網上提供的免費統計功能,好比cnzz的統計,好比google分析,好比百度統計,關鍵的是,好多統計爲了保證統計效果,可能會建議用戶將統計代碼放在頁面的頭部。若是用戶選擇這麼作,可能會在統計代碼請求數據不穩定時給他的網站用戶帶來很是很差的體驗。不過,目前大部分統計服務都容許你以異步方式載入放在頭部的JS文件,在很大程度上解決了這一問題。

6、把你的JavaScript打包成PNG文件

這個辦法是最近在網上看到老外的一種作法,思惟很特別,尚未嘗試過,有興趣的朋友能夠嘗試一下。具體是這樣:把你的JS和CSS添加到圖片的末尾,而後用CSS來裁切,經過一次HTTP請求來得到應用程序中所需的全部信息,它把你的JavaScript/css數據打包成PNG文件,而後你還能夠拆包,只要使用畫布API的getImageData()。這種方法效率很是高,能夠在不縮小數據的狀況下,多壓縮35%左右。

JS動態加載JS與CSS文件

 

DEMO

一 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 Document
function 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>.

應用:一、提升代碼的複用,減小代碼量;二、添加一個javascript控制器和 session能夠實現動態改變頁面樣式;三、因爲是頁面是從上到下依次加載文件的,而且邊加載邊解釋,因此能夠添加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.

相關文章
相關標籤/搜索