Javascript preload images CSS js method examples

  • 2020-03-26 21:25:17
  • OfStack

The advantage of preloading can make the web page faster to present to the user, the disadvantage is that it may increase useless requests (but images, CSS, js and other static files can be cached), if the user visits the page CSS, js, images are preloaded, the user will open the page much faster, improve the user experience. When using large images, preloading large images is a good way to get them to the user faster. Without further explanation, as a front end siege engineer, I will share my tests and results.

First, the status code returned by the server that you need to know:
Status-code: 200 - client request successful
Status-code: 304 - the file is already in the browser cache, and the server tells the client that the previously cached document can still be used.
This test determines whether the file is cached by determining whether it returns 304.

The following is a test for several methods of preloading, including new Image(), object, and iframe, loading img/js/ CSS in different browsers. The following load test js, CSS, image files, from several portal sites found (why find a few? To test for as many special cases as possible.
1. The test is preloaded with new Image()
1.1 load new Image()


    new Image().src = 'http://img02.taobaocdn.com/tps/i2/T1iQhUXnxpXXXXXXXX-171-48.png'; // taobao 
    new Image().src = 'http://static.paipaiimg.com/module/logo/logo_2011_02_22.png'; // pat 
    new Image().src = 'http://co.youa.baidu.com/picture/services/images/logo.png'; // yes 
    new Image().src = 'http://img1.t.sinajs.cn/t35/style/images/common/header/logoNew_nocache.png'; //Sina * /

Then add the image to the page: < Img SRC = "XXX" / >

Load the picture there is nothing to say, ie6-9 /CM/FF/OP/ all return 304, preload success.
1.2. Test the CSS with new Image()


    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'; //Clap (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 to test if the time set by Expires in IE is less than the current time

Add CSS to the page

CM/OP, both return 304
FF, only 5 returns 304, and only 5 http-headers are the simplest (including: Date, Server, Expires, cache-control).
The others all have a lot of header information, but they all set the ones in 5. Looking for a pattern, I found that the other responses all had: content-type :text/javascript, while 5 did not.
IE, 2/5 returns 304, 1/3/4 returns 200, so it's still content-type compared to the response header, so 2/5 doesn't see content-type in IE.
In addition, thanks to AndrewZhang (http://www.cnblogs.com/AndyWithPassion/), IE the image under preloading js httpwatch check the content, resource loading is not complete. The same goes for my tests here. There seems to be a byte limit, in the test 2 returned complete, and part of the 5 was lost. So loading JS with new Image is not a good idea at all.

Here's the bottom line: preloaded images are compatible with new Image(). However, CSS /js only works with OP/CM, IE/FF is basically invalid (IE/FF is tacit).
2. The test was preloaded with object

Then, the data in the object load file, create a label to add to the HTML test.

Test results:
FF/OP/CM: returns 304 for both img/js/ CSS.
Ie6-8: load img/js/ CSS with object, Aborted directly.
IE9 is special:
IE9 loads js/ CSS, requests and returns HTTP200, then requests and Aborted, which is actually one request.
In the case of IE9 loading img, first request and return HTTP200, and then request to return the image, so the image needs to be requested twice.

The first request for IE9 returned empty content (and at this point the browser typically got stuck or simply lost). IE9 will first request the url, get the file type, judge JS/CSS on Aborted, judge is the image to load.

As for IE9's first request, it probably relies on reading the HTTP header to get the file type, or secretly downloading the file and testing the file type in the sandbox.
An interesting thing, such as loading JS with object, IE9 can also load in sometimes, that is, the first request did not identify the file is JS (want to see this is luck, it seems to happen when the network speed is slow)

It is said that IE used to judge the file type by the file suffix, and later used the HTTP header information to judge, and they can be forged, so there is a security problem with object under IE.
Ie6/7, if the file suffix.js/.css will not make the request, if changed to http://xxx/test.js? 123.png, sends the request, then introduces it with the script tag, and finds that it can be cached (CSS is OK^^).
IE8, the suffix js/ CSS will not make a request, change the suffix to PNG can make a request and get the content, and then the page to create a label to introduce, the file is not cached. But if the file is a real image it's cached.
Digression: as you can see from the above, security has increased with the upgrade of IE.

So, here is the conclusion: FF/OP/CM can use object preload, IE is never used.
3. Test with iframe preload

Create the page a.html and then add the following js.


    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 is of course best triggered after window.onload
            //To trigger onload, first appendChild, then onload (IE can't be triggered if the order is reversed)
            // ifm.onload = function(){ alert('ifm loaded'); }
            //Contentwindow.document - all supported, contentdocument-ie9 /FF/OP/CM supported
            var ifmDoc = ifm.contentDocument || ifm.contentWindow.document;
            ifmDoc.open();
            ifmDoc.write('<!doctype><html><head></head><body>');
            //ifmDoc.write('<style>html{background:#000;color:#fff}</style>'); //  Used for testing 
            //ifmDoc.write('<script>alert("a")</script>'); //  Used for testing 
            //ifmDoc.write('<p>test</p><p>test</p><p>test</p><p>test</p><p>test</p>');//  Used 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 that IE is dead.
            ifmDoc.write('<img width="1" height="1" src="http://localhost/123.png?2011" />');
            ifmDoc.write('</body></html>');
            ifmDoc.close();
    };

Then create a new page, b.html, and add the file you want to preload to the HTML to test if it's already preloaded.
Results: IE/FF/OP/CM were preloaded successfully.

Note: when a.html is opened and the page is refreshed, the iframe loads the file.
FF, returns 200(note that this 200 is not the 200 returned by the server, but the request was cached successfully. Because the time of sending the request is 0).
CM, the status is (from cache).
OP, although the display state is n/a, is also from cache. IE, IE's built-in debugging tool shows 304, HttpWatch shows 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: debugging tools that come with IE9, HttpWatch, firebug, debugging tools that come with chrome, Opera Dragonfly.

The final conclusion is that new Image() is nearly enough for js preloaded images. But CSS, js is a little special, using object needs to judge the browser. If you consider that js, CSS, and img are compatible for preloading, consider using an iframe.

In addition, the above method to create an iframe, do not use the write () writes to load the file, set the iframe directly. The SRC = "cache. HTML", then write to preload files in the cache. HTML is feasible, have seen the article introduces the sina weibo did this, but can't find my articles address, didn't search search), I collect the cache's web site: http://tjs.sjs.sinajs.cn/miniblog2/static/html/cache.html, but look at weibo homepage didn't find this, don't know which page in use.
A little addition to other preloads

Doc.createelement ('script') can preload js, and if there is an action on the page in js, it will affect the page.
Doc.createelement ('link') can preload CSS, but it may also have an impact on the style of the current page.
So this is not a good way to preload.
Load img/js/ CSS with ajax, compatibility is good, files can be cached, but only limited to the same domain, so the scope of use is limited.
Preloaded images can also be implemented using CSS background images. Awesome lifesinger has previously written about HTTP requests for images, but his blog's previous data is gone. An online search turned up an article: (link: #). The article mentioned the use of background images and hidden img tags to preload, the conditioning is very clear. Can also serve as a reference.

In addition, the imitation of sina's cache.html to write their own, if you like to use iframe as a separate file can be used as a reference.


    <!DOCTYPE html><html><head><meta charset="utf-8"></head><body>
    <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 errors
    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>
    <img src="http://xxx/4.png" />
    </body></html>


Related articles: