Last active
December 6, 2016 16:05
-
-
Save nuxodin/39105245ffb598debf6b to your computer and use it in GitHub Desktop.
ensure image ratio before load
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
// ussage: | |
// - include this script | |
// - add the data-c1-ratio-attribute to your images | |
// <img src="big.jpg" data-c1-ratio="1.245" style="width:200px; max-width:100%"> | |
!function(){ | |
'use strict'; | |
var listener = function(e){ | |
this.removeEventListener('load',listener); | |
this.removeEventListener('error',listener); | |
this.src = this.c1RealSrc; | |
} | |
function calc(){ | |
var all = document.querySelectorAll('[data-c1-ratio]'), | |
i = 0, el, ratio; | |
for (;el=all[i++];) { | |
if (el.complete) continue; | |
ratio = el.getAttribute('data-c1-ratio'); | |
if (!ratio) return; | |
if (el.c1RealSrc) return; | |
el.c1RealSrc = el.src; | |
el.addEventListener('load',listener); | |
el.addEventListener('error',listener); // not working in ie 11, bad browser | |
el.src = 'data:image/svg+xml;utf8,'+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="'+ratio*1024+'" height="1024" style="background:rgba(222,222,222,.2);"></svg>'); | |
} | |
} | |
window.requestAnimationFrame && requestAnimationFrame(calc); | |
document.addEventListener('DOMContentLoaded',calc); | |
// todo: mutation observer? | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment