5

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?

Jason
  • 210
  • 1
  • 8

1 Answers1

5

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.

alexander farkas
  • 13,754
  • 4
  • 40
  • 41
  • Thanks! I had to then make further adjustments for cross-browser support. – Jason Jan 02 '15 at 18:36
  • 1
    Would like to know, what you needed to change. – alexander farkas Jan 10 '15 at 14:54
  • @jason What cross-browser changes did you need to make? – Jonathan Aquino Jul 22 '15 at 00:04
  • heya, maybe this can be helpful...it's been a while and I adjusted the above for a more specific use case. I can get back into this head space, but here are some snippets for reference. – Jason Jul 23 '15 at 21:06
  • 1
    // Complete is true after image is loaded. IE11 does not fire load when // image is cached so we trigger load event ourselves. if (this.complete) { $(this).load(); } – Jason Jul 23 '15 at 21:07
  • 1
    // In IE9 or IE10, complete is false and load is not fired. // Reset the image source attribute to trigger load event. if (document.documentMode === 9 || document.documentMode === 10) { image.attr('src', $(image).attr('src')); } – Jason Jul 23 '15 at 21:07