Skip to content

Instantly share code, notes, and snippets.

@ronny
Created September 17, 2012 01:09
Show Gist options
  • Save ronny/3735069 to your computer and use it in GitHub Desktop.
Save ronny/3735069 to your computer and use it in GitHub Desktop.
Async image loading
// Loads images asynchronously so that the page would be displayed quicker.
//
// Define images with <img class="async" data-src="http://example.com/img.jpg">,
// and when load is called, all of the images' src attribute will be set from
// their data-src attribute.
var AsyncImagesLoader = {
init: function() {
AsyncImagesLoader.timeout = setTimeout(AsyncImagesLoader.load, 0);
},
// Replace every img.async's src with its data-src.
load: function() {
// Get elements by class or tagname is faster than by selector like img[data-src].
var elms = document.getElementsByClassName('async');
var elmCount = elms.length;
for (var i=0; i < elmCount; i++) {
var elm = elms[i];
var src = elm.getAttribute('data-src');
if (typeof src !== "undefined" && src !== null) {
elm.setAttribute("src", src);
}
}
}
};
// Uncomment the next line, or place it in your code somewhere, if you want
// load to be called when DOM 'load' is fired by the browser. Using
// DOMContentLoaded instead of load probably wouldn't work.
// window.addEventListener('load', AsyncImagesLoader.init);
//////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2012 PlayUp, Ben Kitzelman, Ronny Haryanto.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@ronny
Copy link
Author

ronny commented Sep 17, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment