1
votes

I'm using Scott Jehl's picturefill to serve up images responsively on my site. My code looks like this:

<div data-picture id="front-image">
    <div data-src="image.jpg"></div>
    <div data-media="(min-width: 600px)" data-src="image-medium.jpg"></div>
    <div data-media="(min-width: 900px)" data-src="image-large.jpg"></div>
    <noscript><img src="image.jpg"></noscript>
</div>

After the page has been processed by Picturefill, the code looks like this:

<div data-picture="" id="front-image">
    <div data-src="image.jpg"></div>
    <div data-media="(min-width: 600px)" data-src="image-medium.jpg"></div>
    <div data-media="(min-width: 900px)" data-src="image-large.jpg"></div>
    <noscript><img src="image.jpg"></noscript>
    <img alt="" src="image-large.jpg">
</div>

Notice the new img tag at the end of the main div; that's the one generated by the script (and in this case since my browser window was large, it's the large image).

I'd like to grab the src of that image, but when I do something like

$(function() {
   var src = $('#front-image img').attr('src');
   // do other stuff with that variable once I have it
});

in a javascript file that is called after Picturefill, the var is empty.

My best guess is that the document is 'ready' and js evaluated before the Picturefill magic happens. How can I make my code wait until Picturefill has done its duty so I can grab the src from that img tag?

[Totally not a javascript person here so obviously if there's another way to go about getting the src or my guesses are completely wrong please correct me!]

3

3 Answers

0
votes

on option is using DOMNodeInserted event, which fires after insertion of a new node element.

$(document).on('DOMNodeInserted', function() {
   var src = $('#front-image > img').attr('src');
})
0
votes

I ended up doing one of the first things @raminson suggested - splicing out a piece of the picturefill script (the part that uses matchmedia, in this case) and using it to figure out which image was correct to load for this screen size.

        $("#front-image div").each(function() {
            var media = $(this).attr( "data-media" );
                if( !media || (matchMedia &&matchMedia( media ).matches ) ){
                    var imgsrc = $(this).attr("data-src");
                    // do stuff with the img src
                }
            });
0
votes

Picturefill is awesome, but I was having some similar challenges with handling of the real images.

I ended up creating the jquery.pikshur plugin that does basically the same thing as picturefill, but gives you a bit more control over the elements, including allowing onLoad events for the images.