2014
Mar
10
Why may we want to preload images?
Preloading images is a great way to improve the user experience. When images are preloaded in the browser, the visitor can surf around your site and enjoy extremely faster loading times. This is especially beneficial for photo galleries and other image-heavy sites where you want to deliver the goods as quickly and seamlessly as possible. Preloading images definitely helps users without broadband enjoy a better experience when viewing your content. In this article, we’ll explore three different preloading techniques to enhance the performance and usability of your site.Soultions To Preload Images
Method 1: With CSS And JavaScript
as Nanda suggests, it is better to preload images using only CSS. Using the CSS background property, we can preload images via existing div, span, or other elements in the (X)HTML markup.
HTML Markup
- <ul id="thumbnails" class="thumbnails">
- <li class="thumbnail"><div class="thumbnail-001 preload"></div></li>
- <li class="thumbnail"><div class="thumbnail-002 preload"></div></li>
- <li class="thumbnail"><div class="thumbnail-003 preload"></div></li>
- <li class="thumbnail"><div class="thumbnail-004 preload"></div></li>
- <li class="thumbnail"><div class="thumbnail-005 preload"></div></li>
- </ul>
CSS
- .preload {
- display: none;
- }
- .thumbnails {
- list-style: none;
- margin: 0;
- padding: 0;
- }
- .thumbnail {
- background: #fafafa;
- border: 1px solid #ccc;
- float: left;
- height: 200px;
- margin: 0 5px 10px 0;
- padding: 2px;
- width: 300px;
- }
- .thumbnail-001 {
- background: transparent url(images/golden_gate_bridge.jpg) no-repeat -500px -200px;
- height: 200px;
- width: 300px;
- }
- .thumbnail-002 {
- background: transparent url(images/harley_davidson_cafe_001.jpg) no-repeat -300px -250px;
- height: 200px;
- width: 300px;
- }
- .thumbnail-003 {
- background: transparent url(images/palace_of_fine_arts.jpg) no-repeat -500px -150px;
- height: 200px;
- width: 300px;
- }
- .thumbnail-004 {
- background: transparent url(images/castro.jpg) no-repeat -500px -350px;
- height: 200px;
- width: 300px;
- }
- .thumbnail-005 {
- background: transparent url(images/pier_39.jpg) no-repeat -500px -150px;
- height: 200px;
- width: 300px;
- }
JavaScript
- var divElements = document.getElementsByTagName("div");
- for (var i = 0; i < divElements.length; i++) {
- var element = divElements[i];
- element.className = element.className.replace(" preload", "");
- }
Method 2: With JavaScript Only
There are some considerations we need to be aware of here:
- It needs to be threaded in parallel (to use the browser’s maximum threads, normally 6 per domain).
- It needs to also be sequential (pipelined) for when you want to use a single thread.
- It needs to handle individual image events –
onload
,onabort
,onerror
. - We need to clean up resources and memory, not leak memory and prevent IE GIF onload from firing multiple times. In Internet Explorer 5/6/7, the onload event fires ALL THE TIME for animated GIFs. That's right, on each animation loop it fires an onload for you. Which is why you need to make sure you release your image objects for GC by not saving a reference – or should you need to store them as objects into a new array – remove all onload and other events attached to them.
HTML Markup
- <div class="progress">
- <div id="progress-bar" class="progress-bar"></div>
- <div id="progress-percent" class="progress-percent"></div>
- </div>
- <ul id="thumbnails" class="thumbnails">
- </ul>
Example
- /********************
- Author: Vivian Huang
- Date: March 10, 2014
- Related Posts
- http://fragged.org/preloading-images-using-javascript-the-right-way-and-without-frameworks_744.html
- http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
- ********************/
- var IMGPRELOADER = function (images, options) {
- var defaults,
- isNative = "addEventListner" in (new Image()),
- index = 0,
- queues = [],
- completed = [],
- errors = [],
- handleLoad,
- handleError,
- handleAbort,
- reset,
- setOptions,
- removeEvents,
- load,
- checkProgress;
- defaults = {
- auto: true,
- onStart: function () {},
- onProgress: function () {},
- onError: function () {},
- onComplete: function () {}
- };
- handleLoad = function () {
- console.log("**** handleLoad ****");
- removeEvents.call(this);
- completed.push(this.src);
- checkProgress(this.src, this);
- };
- handleError = function () {
- console.log("**** handleLoad ****");
- removeEvents.call(this);
- errors.push(this.src);
- checkProgress(this.src, this);
- options.onError(this.src);
- };
- handleAbort = function () {
- console.log("**** handleAbort ****");
- removeEvents.call(this);
- errors.push(this.src);
- checkProgress(this.src, this);
- options.onError(this.src);
- };
- reset = function () {
- index = 0;
- queues = completed = errors = [];
- };
- setOptions = function (options) {
- for (var key in defaults) {
- if (!options.hasOwnProperty(key)) {
- options[key] = defaults[key];
- }
- }
- return options;
- };
- removeEvents = function () {
- if (isNative) {
- this.removeEventListner("load", handleLoad);
- this.removeEventListner("error", handleError, false);
- this.removeEventListner("abort", handleError, false);
- } else {
- this.onload = this.onerror = this.onabort = null;
- }
- };
- load = function () {
- if (index >= queues.length) {
- return;
- }
- var image = new Image(),
- src = queues[index];
- if (isNative) {
- image.addEventListner("load", handleLoad, false);
- image.addEventListner("error", handleError, false);
- image.addEventListner("abort", handleError, false);
- } else {
- image.onload = handleLoad;
- image.onerror = handleError;
- image.onabort = handleError;
- }
- image.src = src;
- };
- checkProgress = function (imgSrc, imgElement) {
- options.onProgress(imgSrc, imgElement, (completed.length + errors.length), queues.length);
- index++;
- load();
- if (index === queues.length - 1) {
- options.onComplete(completed, errors);
- }
- };
- (function () {
- options = (options && typeof options === "object") ? setOptions(options) : defaults;
- queues = (images && images instanceof Array) ? images.slice() : [];
- options.onStart(queues);
- if (queues.length && options.auto) {
- load();
- }
- })();
- };
Example
- // For IE < 8
- if (!Array.prototype.map) {
- Array.prototype.map = function(fun /*, thisp*/) {
- var len = this.length;
- if (typeof fun != "function") {
- throw new TypeError();
- }
- var res = new Array(len);
- var thisp = arguments[1];
- for (var i = 0; i < len; i++) {
- if (i in this) {
- res[i] = fun.call(thisp, this[i], i, this);
- }
- }
- return res;
- };
- }
- var imagesArray = new Array(20).join(",").split(","),
- progressBarElement = document.getElementById("progress-bar"),
- progressPercentElement = document.getElementById("progress-percent"),
- thumbnailsElement = document.getElementById("thumbnails");
- imagesArray = imagesArray.map(function(el, i) {
- return "images/golden_gate_bridge.jpg?" + +new Date() + i;
- });
- imagesArray.push("images/golden_gate_bri.jpg");
- var preloader = new IMGPRELOADER(imagesArray, {
- onStart: function (images) {
- console.log("**** onStart ****");
- console.log(images);
- },
- onProgress: function (imgSrc, imgElement, progressed, total) {
- console.log("**** onProgress ****");
- var defaultWidth = 200,
- ratio = 1,
- width = imgElement.width,
- height = imgElement.height,
- percent = 0;
- if (width > defaultWidth) {
- ratio = defaultWidth / width;
- height = Math.round(height * ratio);
- width = defaultWidth;
- }
- var liElement = document.createElement("li");
- liElement.className = "thumbnail";
- liElement.innerHTML = '<img src="' + imgSrc + '" width="' + width + '" height="' + height + '">';
- thumbnailsElement.appendChild(liElement);
- percent = Math.floor(progressed / total * 100) + "%";
- progressBarElement.style.width = percent;
- progressPercentElement.innerHTML = percent;
- },
- onError: function (imgSrc) {
- console.log("**** onError ****");
- console.log(imgSrc);
- },
- onComplete: function (loaded, errors) {
- console.log("**** onComplete ****");
- console.log(loaded);
- console.log(errors);
- }
- });
回應 (Leave a comment)