Last active
August 29, 2015 13:57
-
-
Save mirceapiturca/9493434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo at http://jsfiddle.net/DLKpJ/3/
Requires promises and custom elements support