Skip to content

Instantly share code, notes, and snippets.

@mirceapiturca
Last active August 29, 2015 13:57
Show Gist options
  • Save mirceapiturca/9493434 to your computer and use it in GitHub Desktop.
Save mirceapiturca/9493434 to your computer and use it in GitHub Desktop.
// Adding a custom .ready() metod on an image to avoid nasty on load callbacks
// One time custom element initialization.
// Create the 'mega-img' proto, extend the HTMLImageElement.prototype
var proto = Object.create(HTMLImageElement.prototype);
proto.ready = function() {
var deferred = Promise.defer();
this.addEventListener('load', function(){
deferred.resolve(this);
}, true);
return deferred.promise;
};
var MegaImg = document.registerElement('mega-img', {
prototype: proto,
extends: 'img'
});
// Normal day to day element creation
// Append the image the the DOM
var xImg = document.createElement('img', 'mega-img');
document.body.appendChild(xImg);
xImg.setAttribute('src', 'http://blogs-images.forbes.com/merrillbarr/files/2014/02/the-walking-dead-.jpg')
// Element is now created and .ready() method can be used for all 'img' that are 'mega-img'
// Ussage:
xImg.ready().then(function(img) {
// img loaded
console.log('img is ready:', 'width: ' + img.width, 'height: ' + img.height)
}, function() {
// something failed
});
@mirceapiturca
Copy link
Author

Demo at http://jsfiddle.net/DLKpJ/3/
Requires promises and custom elements support

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