JavaScript pre-loading pictures, CSS, JS method examples introduce _javascript tips

Source: Internet
Author: User
Tags script tag browser cache

The benefits of preload allow the web to be rendered faster to the user, the disadvantage is that may add useless requests (but pictures, CSS, js these static files can be cached), if the user visited the page inside the CSS, JS, pictures were preloaded, users open the page will be much faster, improve the user experience. In the use of some large picture display, preload large image is a good way, the picture is presented to the user faster. Not much to say, as a front-end siege master understand, the following share my test and get results.

First, the status code returned by the server that needs to be known:
STATUS-CODE:200-Client Request succeeded
status-code:304-The file is already in the browser cache, and the server tells the client that the previously buffered document can still be used.
This article tests to determine whether the file is cached, using is to determine whether to return 304.

The following several preload methods, in different browsers loaded IMG/JS/CSS to do a test, mainly including new Image (), object, IFrame. The following load Test js, CSS, picture files, from a number of portal sites to find (why to find a few?) In order to test as much as possible to a particular situation, the test is actually encountered.
1. Test with new Image () preload
1.1, new Image () load

Copy Code code as follows:

New Image (). src = ' yun_qi_img/t1iqhuxnxpxxxxxxxx-171-48.png '; Taobao
New Image (). src = ' yun_qi_img/logo_2011_02_22.png '; Pat
New Image (). src = ' yun_qi_img/logo.png '; Yes, it is.
New Image (). src = ' yun_qi_img/logonew_nocache.png '; Sina * *

Then add the picture to the page:

Loading pictures Nothing to say, ie6-9/cm/ff/op/all return 304, preload succeeded.
1.2, the test with new Image () loaded CSS

Copy Code code as follows:

New Image (). src = ' http://a.tbcdn.cn/p/global/1.0/global-min.css '; Taobao (1)
New Image (). src = ' http://static.paipaiimg.com/member/activate.css '; Pat (2)
New Image (). src = ' http://co.youa.baidu.com/picture/services/base.css '; Yes (3)
New Image (). src = ' http://img1.t.sinajs.cn/t35/skin/skin_008/skin.css '; Sina (4)
Http://auto.sina.com.cn/css/newstyles.css
You can use this test to set the time under IE expires less than the current time

Add CSS to the page

Here's the difference:
Cm/op, both return 304 (regardless of whether there is no set expires).
FF, all returned 200.
IE,1/2/4 returns 304, while 3 returns 200. Comparing the returned Http-header, you can find that 1/2/4 has set the expires expiration time, and 3 is not set.
Description IE cache needs to be set expires (and the time is greater than the current time), and FF does not support the use of new Image () preloaded.
1.3, test with new Image () loaded JS

Copy Code code as follows:

New Image (). src = ' http://a.tbcdn.cn/s/kissy/1.1.6/kissy-min.js '; Taobao (1)
New Image (). src = ' http://static.paipaiimg.com/js/pp.noticeBoard.js '; Pat (2)
New Image (). src = ' http://co.youa.baidu.com/picture/services/cms_core.js '; Yes (3)
New Image (). src = ' http://js.t.sinajs.cn/t35/miniblog/static/js/top.js '; Sina (4)
New Image (). src = ' http://shop.qq.com/act/static/week/fri/bang/day_1_p_0_10.js '; QQ (5)

And then add JS to the page.

CM/OP, all returned 304
FF, only 5 returned 304, and only 5 of the Http-header were the simplest (including Date, Server, Expires, Cache-control).
Several other response headers are more informative, but they are all set in 5. Find the law, found that the other several response head are: Content-type:text/javascript, and 5 inside does not have this.
IE,2/5 returned 304,1/3/4 Return 200, contrast response head, should still be content-type influence, ie inside 2/5 did not see Content-type.
In addition, thanks to Andrewzhang (http://www.cnblogs.com/AndyWithPassion/) mentioned, ie under image preload JS under HttpWatch view content, the loading of resources is not complete. So is my test here. There appears to be a byte limit, 2 of the test returned is complete, and 5 of the content is missing. So it is not advisable to load JS with new image.

Here's a summary: pre-loading pictures with new image () compatibility is OK. But Css/js only op/cm can, IE/FF Basic is invalid (this ie/ff to quite have tacit understanding).
2. Pre-loading test with Object

    var doc = document,
            obj = Doc.createelement (' object ');
           //obj.data = ' 123.js ';//ps: This write op is invalid ( will use the contents of data as the text node in the OBJECT tag
           // Obj.setattribute (' Data ', ' 123.js '); IMG, CSS, js
            obj.style.cssText = ' Position: absolute;top:-1px;width:1px;height:1px; ';
           //obj.style.width = Obj.style.height = 0;
            doc.body.appendChild (obj);//Insert Object tags need to be inserted into the non-head section to trigger load */
           //obj.onload = function () {alert (' Loaded ')}; Ff/op/webkit Support (if data is a picture, IE9 can also)

Then the object inside the data loaded files, create tags added to the HTML test.

Test results:
FF/OP/CM: Either Img/js/css, return 304.
Ie6-8: Load Img/js/css with object, will be directly aborted.
IE9 is more Special:
IE9 load Js/css, first request and return HTTP200, and then request and aborted, this is actually requested 1 times (2nd time aborted).
IE9 load img Situation, first request and return HTTP200, and then request to return the picture, so the picture needs to request 2 times.

The 1th request returned by IE9 is empty (and the browser usually gets stuck or loses its response directly). IE9 will first request URL, get file type, Judge is js/css on aborted, judge is the picture is loaded.

As for the IE9 1th request, presumably by reading HTTP headers to get the file type, or secretly downloaded the file, and then in the sandbox to test the file type.
An interesting thing, such as the use of object loading JS,IE9 sometimes can also load in, that is, the 1th request did not determine the file is JS (want to see this depends on luck, seemingly slow speed when it may occur)

It is said that the previous IE relied on file suffixes to determine the file type, later use HTTP header information to judge, and they can be forged, so object in IE under the security problem.
IE6/7, if the file suffix suffix is. js/.css does not make a request, if changed to Http://xxx/test.js?123.png, then send the request, and then introduced with the script tag, found can be cached (CSS is also ok^^).
IE8, the suffix of js/css also does not make a request, the suffix of PNG can be issued to request and get content, and then page creation tag introduced, the file is not cached. But if the file is a real picture, it is cached.
Digression: Through the above can be found, with IE upgrade, security is also getting higher.

So, the conclusion here is: FF/OP/CM can be loaded with object, IE will never use.
3. Pre-loading with IFRAME for testing

First create the page a.html, then add the following JS.

Copy Code code as follows:

var doc = document,
IFM = Doc.createelement ("iframe");
Ifm.id= "PRELOADIFM";
Ifm.style.border = Ifm.width = Ifm.height = 0;
Ifm.style.cssText = ' position:absolute;top:-10px;border:0;width:1px;height:1px; ';
ifm.scrolling = "No";
Doc.body.appendChild (IFM);
Window.onload = function () {//preload of course preferably after window.onload trigger
To trigger the onload, you need to first appendchild, and then write the onload (if the order is reversed, ie can not trigger)
Ifm.onload = function () {alert (' IFM Loaded ');}
contentwindow.document-all support, CONTENTDOCUMENT-IE9/FF/OP/CM support
var ifmdoc = Ifm.contentdocument | | Ifm.contentWindow.document;
Ifmdoc.open ();
Ifmdoc.write (' <!doctype>Ifmdoc.write (' <style>html{background: #000; color: #fff}</style> '); For testing
Ifmdoc.write (' <script>alert (' a ') <\/script> '); For testing
Ifmdoc.write (' <p>test</p><p>test</p><p>test</p><p>test</p> <p>test</p> ');//For testing
Start loading
Ifmdoc.write (' <link rel= "stylesheet" href= "http://localhost/123.css?2011"/> ");
Ifmdoc.write (' <script defer src= ' http://localhost/123.js?2011 ' ><\/script> '); Without defer, you will find IE card dead.
Ifmdoc.write (' ");
Ifmdoc.write (' </body>Ifmdoc.close ();
};

Then create a new page b.html, add the pre-loaded file to the HTML, and test whether it has been preloaded.
Results: IE/FF/OP/CM were successfully preloaded.

Need to explain: when open a.html, and then refresh the page, the IFRAME Nega the case of the file.
FF, return 200 (note that this 200 is not the 200 returned by the server, and is the request cache success.) Because the time to send the request is 0.
CM, the display status is (from cache).
OP, although the display status is N/A, but also from cache. Ie,ie's own debug tool shows 304,httpwatch display from cache.

Test environment:
WIN7 EN Sp1:op 11.50, ie7-9, FF 3.6/6.0, Chrome 10
XP EN Sp3:ie6
XP EN Sp3:ie7
XP CN SP3:IE8
Tools: IE9 Debugging Tools, HttpWatch, Firebug, chrome-led Debugging tools, Opera Dragonfly.

Finally come to the conclusion: JS pre-loading pictures using new image () is basically enough. But CSS, JS special, use object needs to judge the browser. If you consider JS, CSS, IMG can be compatible with the implementation of preload, you can consider the use of IFRAME.

In addition, the above method creates an iframe and does not use write () to write to the file to be loaded, setting IFRAME.SRC = "cache.html" directly, Then the file to be preloaded in cache.html is also feasible (previously seen an article introduced Sina Weibo is done, but the article address can not find, search also did not found), the cache URL I collected: http://tjs.sjs.sinajs.cn/ Miniblog2/static/html/cache.html, but look at Weibo's homepage did not find this, do not know which page to use.
Additional preload for a little supplement

Doc.createelement (' script ') can preload JS, if JS inside there is the operation of the page, will have an impact on the page.
Doc.createelement (' link ') can preload the CSS, but it may also affect the style of the current page.
So preloading is not very desirable.
With Ajax load IMG/JS/CSS, compatibility is good, files can be cached, but only limited to the same domain, so the use of a limited scope.
Pre-loading pictures can also be implemented using CSS background images. Niu Lifesinger has written about the HTTP request of the picture before, but his previous data is gone. Online Search to an article: http://www.jb51.net/web/110275.html. The article mentions the use of background graphics and hidden img tags to preload, conditioning is very clear. can also be used as a reference.

In addition, The imitation of Sina Cache.html himself wrote a, if like to use the IFRAME as a stand-alone document can be used as a reference.

Copy Code code as follows:

<! DOCTYPE html><script>
Usage:cache.html?v=123
var win = window,
Doc = document,
Head = Doc.getelementsbytagname ("head") [0],
Getquery = function () {
var ret = {},
Sch = Win.location.search,
Arr
tmp
if (Sch) {
Sch = Sch.substr (1);
arr = Sch.split ("&");
for (var i = 0, j = arr.length I < J; i++) {
TMP = arr[i].split (' = ');
Ret[tmp[0]] = tmp[1];
}
}
return ret;
},
Version = Getquery (). V | | '';
Win.onerror = function () {return true}; Block JS Error Tips
Win.onload = function () {
var B = doc.createelement ("script");
B.SRC = ' http://xx/1.js?v= ' + version;
Head.appendchild (b);
//...
};
Doc.write (' <link rel= "stylesheet" href= "http://xxx/3.css?version= ' + version + '" \/> ');
</script>

</body>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.