{"id":7636,"date":"2016-04-25T12:01:00","date_gmt":"2016-04-25T12:01:00","guid":{"rendered":"https:\/\/www.htmlgoodies.com\/uncategorized\/so-you-want-to-pre-load-huh\/"},"modified":"2021-04-23T21:23:48","modified_gmt":"2021-04-23T21:23:48","slug":"so-you-want-to-pre-load-huh","status":"publish","type":"post","link":"https:\/\/www.htmlgoodies.com\/design\/so-you-want-to-pre-load-huh\/","title":{"rendered":"So, You Want To Pre-Load, Huh?"},"content":{"rendered":"
Original article by Joe Burns, updated by Rob Gravelle<\/p>\n
Have you ever noticed that pages you’ve already visited always load faster than one that you’re viewing for the first time? The reason that page content loads so fast the second time around is that they’ve been cached by the browser. The first time that the browser opens a page, that HTML document and associated resources are all written to the cache for later use. The next time you navigate to that page, the browser knows it can load the page and resources from the cache rather than re-fetching the files from the server.<\/p>\n
Knowing that downloading an image primes it for faster delivery on the next request, we can force the browser to download images for later use early on in the page loading process. That technique is called image preloading and is the subject of this tutorial.<\/p>\n
The primary reason that you would want to pre-load images would be to increase responsiveness, as in, decrease noticeable time lags. You might think that, in this day and age, most people have a fast enough connection to make image preloading unnecessary, but that’s not entirely true. Consider the mouseover event; if you change image on the :hover state, downloading will only be initiated on the first :hover event. Hence, there may be a perceptible delay there. Large image files may also take a second or two to load. Preloading those images early rather than later helps ensure that visitors have a great experience viewing your content.<\/p>\n
Caching pages is a good practice, but don’t go overboard. Caching every image up-front will certainly take longer than just downloading the current page images and such. You can try to get around that by only caching what will be needed for the next few pages rather than trying to squeeze everything through the Internet pipe at once.<\/p>\n
Another consideration is whether you’re preloading using HTML, CSS or JavaScript. As we’ll see shortly, each has their own pros and cons. For instance, preloading with CSS tends to make fewer HTTP requests than JavaScript and works even if the user’s browser has disabled JavaScript (not that anyone does that anymore!). CSS-driven image preloading may also help speed up the rendering of your site as you probably already have a bunch of JavaScript running on the page load.<\/p>\n
With that in mind, let’s explore each technique in detail.<\/p>\n
Most commonly utilized to define a link between a document and an external resource, such as a CSS file, the <link> tag also provides a mechanism for performing predictive lookups and fetching of resources. The latter includes a couple of options for preloading images, one that’s been around for a while, and another that’s much a more recent addition.<\/p>\n
Let’s begin with the most established one. It sets the rel attribute to “prefetch”, using the following basic format:<\/p>\n
<link rel=\"prefetch\" href=\"(url)\">\n<\/pre>\nThis directive tells the browser to fetch a resource that will probably be needed for the next navigation. That means that the resource will likely be fetched with extremely low priority since everything that’s required in the current page takes precedence over a resource on the next page. That makes prefetch far more suited to speeding up the next page rather than the current one.<\/p>\n
On the other hand, the new “preload” rel value targets current navigation. It also supports the extra “as” attribute, that tells the browser what it will be downloading. Possible “as” values include:<\/p>\n
We can use preload to load images ahead of time, along with the media attribute in order to restrict the downloading of an image to devices of a certain resolution:<\/p>\n
<link rel=\"preload\" as=\"image\" href=\"map.png\" media=\"(max-width: 600px)\">\n<\/pre>\nWhile the prefetch directive is supported by most major browsers, with the exception of Safari and Opera Mini, preload is only supported by Chrome and Opera, making it too early to adopt right now.<\/p>\n
CSS Preloading<\/h2>\n
CSS has been a viable way to preload images ever since the inclusion of the background-image attribute. Since then CSS2 and CSS3 have continued to add ever more options.<\/p>\n
As you contemplate using the following techniques, consider that:<\/p>\n
<\/p>\n
Therefore, when you need the image to be available will determine whether to use a CSS-only solution. Unless you need an image right away, it should suffice.<\/p>\n
This is the most cutting edge solution at this time, using the :root (or body) selector along with the :before or :after pseudo-selector. Both the :before and :after selectors have an attribute named “content” that can be set to one or more URLs, allowing us to preload all of our images with one rule. This technique works great in supportive browsers now, with support only getting better as time goes on. It also works regardless of document structure because images are associated to an element that is guaranteed to exist – the entire document:<\/p>\n
<style>\n\/* body:before will also work\n as will body:after *\/\n:root:before {\n content: url(\/@\/Storage\/_files\/68\/file.jpg)\n url(\/@\/Storage\/_files\/62\/file.gif)\n url(\/@\/SiteBuilder\/_skins\/5\/images\/menu\/ro\/photos.gif);\n \/* partial fallback *\/\n background-image: url(\/@\/Storage\/_files\/68\/file.jpg);\n visibility: hidden;\n position: absolute;\n left: -999em;\n}\n<\/style>\n<\/pre>\nNotice that we can include a partial fallback mechanism by preloading one of the images as a single background property value. Browsers that don’t accept multiple URLs will fallback to the single-value background property instead.<\/p>\n
We are also using a few tricks to prevent the images from displaying right away, including the use of “visibility: hidden”. It has been found to be more reliable than “display: none”, which could prevent the preloading of the resource. Finally, the image is positioned off-screen just in case that it were to display after preloading.<\/p>\n
Keep in mind that Internet Explorer (8+) only supports the content property if a valid DOCTYPE (<!DOCTYPE HTML>) is specified.<\/p>\n
Setting an Element’s Background Image(s)<\/h3>\n
An alternative to setting the content of a :before or :after pseudo-selector is to set an element’s background image(s). The following example uses the shortcut background attribute, of which background-image is one property, along with the repeat and positioning properties. Much like the content attribute, background accepts multiple URLs in most modern browsers, except that these are separated by commas:<\/p>\n
body {\n background: url(\/@\/Storage\/_files\/68\/file.jpg) no-repeat -9999px -9999px,\n url(\/@\/Storage\/_files\/62\/file.gif) no-repeat -9999px -9999px,\n url(\/@\/SiteBuilder\/_skins\/5\/images\/menu\/ro\/photos.gif) no-repeat -9999px -9999px;\n \/* partial fallback *\/\n background: url(\/@\/Storage\/_files\/68\/file.jpg) no-repeat -9999px -9999px;\n}\n<\/pre>\nAgain, off-screen positioning is employed to prevent images from displaying after preloading.<\/p>\n
JavaScript Preloading<\/h2>\n
JavaScript includes the Image among its native object types. The Image object represents an HTML image tag on the page and exposes the same properties and events. Perhaps oddly, the Image has no constructor that accepts an image source, so an image must be loaded into the object by setting its src attribute. Doing so causes the image to be downloaded from the server at that point.<\/p>\n
<script type=\"text\/javascript\">\nvar my_image = new Image();\nmy_image.src = 'mycoolimage.jpg';\n<\/script>\n<\/pre>\n