[JS] Image preload

The way a browser normally works, images are loaded only after an HTTP request is sent for them, either passively via an tag or actively through a method call.

所以這就是為什麼圖片都會有Delay抓不到的情況…因為他通常是被觸發時才會自動去抓src的圖。可是如果真的是這樣的話,那就要想個辦法來避免這個問題。不過該怎麼辦咧?

The simplest way to preload an image is to instantiate a new Image() object in JavaScript and pass it the URL of the image you want preloaded , and load it simultaneously to the page with the onLoad() event handler:

哦酷哦,直覺上的想法就是要讓頁面load完時就先onload 一個function,這樣就可以把執行時間提前,因此只要寫個function包起來讓onload去讀就可以了。

DEMO CODE:
http://gist.github.com/251380.js?file=gistfile1.js

Leave a Reply

Your email address will not be published. Required fields are marked *