I have a need to re-use the rendered image of a picture element. Is there a direct way to use javascript to access the image file path rendered by chrome/opera without having to replicate the logic that picturefill completes.
<picture>
<source media="(min-width: 800px)" srcset="head.jpg, head-2x.jpg 2x">
<source media="(min-width: 450px)" srcset="head-small.jpg, head-small-2x.jpg 2x">
<img src="head-fb.jpg" srcset="head-fb-2x.jpg 2x" >
</picture>
Using the example above, on a retina desktop browser window with a width of 1200px, a browser with picture support will render head-2x.jpg. Or, if I'm using chrome browser on a smart phone with width less than 450px with retina display, it would use head-fb-2x.jpg. How can I access this dynamically rendered image directly?
Is there a way to access this rendered image without having to parse the source elements myself?
There is the currentSrc
proprety, which is only updated, if the candidate was loaded. A function could look something like this:
function getCurrentSrc(element, cb){
var getSrc;
if(!window.HTMLPictureElement){
if(window.respimage){
respimage({elements: [element]});
} else if(window.picturefill){
picturefill({elements: [element]});
}
cb(element.src);
return;
}
getSrc = function(){
element.removeEventListener('load', getSrc);
element.removeEventListener('error', getSrc);
cb(element.currentSrc);
};
element.addEventListener('load', getSrc);
element.addEventListener('error', getSrc);
if(element.complete){
getSrc();
}
}
Note: you have to pass the img
DOM element and a callback function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With