星期六, 12月 21, 2013

Loading Scripts Without Blocking

最近同事發現有隻script會block其他request
查了一下原來script還真有這問題
在「Even Fast Web Sites」有提到
SCRIPT tags have a negative impact on page performance because of their blocking
behavior. While scripts are being downloaded and executed, most browsers won’t
download anything else. There are times when it’s necessary to have this blocking, but
it’s important to identify situations when JavaScript can be loaded independent of the
rest of the page.

可以實際試一下
http://stevesouders.com/cuzillion/?ex=10008&title=Scripts+Block+Downloads









作者的說明是...
This page has two scripts at the top, A.js and B.js, followed by an image, a stylesheet, and an iframe. The scripts are each programmed to take one second to download and one second to execute. The white gaps in the HTTP profile indicate where the scripts are executed. This shows that while scripts are being downloaded and executed, all other downloads are blocked. Only after the scripts have finished are the image, stylesheet, and iframe merrily downloaded in parallel.

中文就是指...
可以看出兩個script會等待,且會block其他requests下載
兩段的空白是script執行時間,完成後才會進行下一步
二個scripts都好了,才會再同時download其他resources

解決方法
作者有提出幾種方法,不過似乎都不能一次解決
書是2009年出的,想說有沒有新的解決方法,google看到了這段

reference: What is a non-blocking script?
  1. create a script node dynamically and
    var scriptElem = document.createElement('script');|
    scriptElem.src = 'http://anydomain.com/A.js';
    document.getElementsByTagName('head')[0].appendChild(scriptElem);
  2. use the HTML5 async attribute of a <script> tag.
    # 我是註解
    <script type="text/javascript" async src="foo.js"> </script>
    
作者有提到要注意script是否有前後執行的順序
特別是處理UI的javascript(UI沒反應or掛了)
因為以上的方法只要下載完就會執行,不管在html裡的順序
ie可設定defer屬性使script同時下載,並依序執行

「Even Fast Web Sites」的作者有建議
後讀的ui相關script要能先呈現loading圖示,避免user使用(lazy-loaded code)
或者可做stub function,先回應空的,等載完後再覆寫