Preloading all assets

alh picture alh · Dec 24, 2013 · Viewed 19.4k times · Source

Is there a single universal way to load all assets before using them? I am wanting to load some images, audio files, and a few .swf files before my app starts. Currently, I load the images by creating new <img> elements and setting the src to the image path, for the audio files I add the preload="auto" attribute in the <audio> tag and I perform an ajax request to load the .swfs.

Is there any problem (re some browsers not caching etc.) with the way I am currently loading my files and is there a 'best practices' way of collectively preloading all these file types before I display my content?

Answer

kumarharsh picture kumarharsh · Dec 27, 2013

Yes. Actually, this has been made into a standard. Here is the relevant RFC. A move to standardise this for HTML5 is in works

Most modern browsers support prefetching. Here is a brief summary of how they are used:

Firefox

As per MDN, you can use the <link> tags in head of the document,

<link rel="prefetch" href="/assets/my-preloaded-image.png">

as well as set HTTP Link header with the request, or within the HTML as a meta tag.

Link: </assets/my-preloaded-image.png>; rel=prefetch
<meta http-equiv="Link" content="</assets/my-preloaded-image.png>; rel=prefetch">
enter code here

Not only this, but you can also give navigation hints within the page, such as what will be the next page, etc.

<link rel="next" href="2.html">

IE 11

In Internet Explorer too there is the Prefetch header. You can set like so:

<link rel="prefetch" href="http://example.com/style.css" />

You can even prefetch (pre-resolve) DNS queries

<link rel="dns-prefetch" href="http://example.com/"/>

Or, prerender a web page (a-la Google Instant)

<link rel="prerender" href="http://example.com/nextpage.html" />

Chrome

Chrome also does the same things as Firefox and IE in this regard.

Safari

I have not been able to find solid proof of whether Safari supports these things. But reading up on many sources, I suspect they do, just that probably Apple is not so eager to market Safari as Microsoft is pushing IE11 (just an opinion).

Have fun. :)

Sources:


Update: After compiling this answer, I stumbled upon a similar answer on SO, which gives more details on the topic. Please do have a look.

How can I preload a page using HTML5?