Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload JS, but don't run it

Tags:

javascript

I want to preload a large JS file after a page has loaded, so that when I link to that JS file on the required page it is already downloaded and cached.

I'm basically doing this at the moment, and it works, but of course it's not the right way:

preload_js = new Image();
preload_js = "http://domain.com/files/file.js";

This seems such a quick and simple method, no Ajax needed etc. and it works great.

What's the proper way to do this? Surely not with Ajax as that seems overkill for this.

I know there's lots of methods for loading JS but they all seem to actually run the code after the script has loaded, which I don't want.

I don't want to use jQuery (or any library), it must be plain JS. Thanks for any help.

like image 355
user2143356 Avatar asked May 17 '13 05:05

user2143356


People also ask

How do I know if preload is working?

If preloading is supported, the request for the image should be made before the JavaScript gets executed, i.e. you should see the request for the image immediately after the one for the HTML document is done.

What does preload JS do in electron?

Summary​ A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node. js environment, and is often used to expose privileged APIs to the renderer via the contextBridge API.

What is preloader in JavaScript?

The preload attribute specifies if and how the author thinks that the media file should be loaded when the page loads. The preload attribute allows the author to provide a hint to the browser about what he/she thinks will lead to the best user experience. This attribute may be ignored in some instances.


2 Answers

From this blog post:

Preloading components in advance is good for performance. There are several ways to do it. But even the cleanest solution (open up an iframe and go crazy there) comes at a price - the price of the iframe and the price of parsing and executing the preloaded CSS and JavaScript. There's also a relatively high risk of potential JavaScript errors if the script you preload assumes it's loaded in a page different than the one that preloads.

After a bit of trial and lot of error I think I came up with something that could work cross-browser:

  • in IE use new Image().src to preload all component types
  • in all other browsers use a dynamic <object> tag

In this example I assume the page prefetches after onload some components that will be needed by the next page. The components are a CSS, a JS and a PNG (sprite).

window.onload = function () {

    var i = 0,
        max = 0,
        o = null,

        // list of stuff to preload
        preload = [
            'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.png',
            'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.js',
            'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.css'
        ],
        isIE = navigator.appName.indexOf('Microsoft') === 0;

    for (i = 0, max = preload.length; i < max; i += 1) {

        if (isIE) {
            new Image().src = preload[i];
            continue;
        }
        o = document.createElement('object');
        o.data = preload[i];

        // IE stuff, otherwise 0x0 is OK
        //o.width = 1;
        //o.height = 1;
        //o.style.visibility = "hidden";
        //o.type = "text/plain"; // IE 
        o.width  = 0;
        o.height = 0;


        // only FF appends to the head
        // all others require body
        document.body.appendChild(o);
    }

};

See the post for more details.


EDIT: Looking at the comments on that post, someone mentions this link, which talks about the problems with the new Image() preload method in IE and other browsers. Here's an excerpt:

When IE encounters an IMG tag, it creates an image object and assigns the download request to it. As data arrives from the image download, it’s fed into the browser's image decoders. The decoders will reject data as malformed if you feed them plaintext, which seems reasonable, since they can't possibly make use of such data. When the decoders reject the data as "Not possibly an image," the image object will abort its processing. As a part of that abort, if the download has not yet completed, it too is aborted.

This explains the behavior mentioned by the OP in the comment below (IE9 only downloading 4KB of the file).

It seems like your only reliable cross-browser option may be to use Ajax...

like image 181
Simon M Avatar answered Nov 08 '22 06:11

Simon M


USE

window.document.onload =function(){
preload_js = "http://domain.com/files/file.js";
}

window.document.onload make sure the java script will not run until you dom is ready

like image 20
Ashisha Nautiyal Avatar answered Nov 08 '22 07:11

Ashisha Nautiyal