Domanda

I'm using picturefill.js (Scott Jehl): https://github.com/scottjehl/picturefill/blob/master/picturefill.js

Here's how I have it setup, (some code omitted b/c it was just more media query stuff) using span tags and data attributes as in his documentation:

<figure>
    <a href='http://www.casaromeromexican.com'>
        <span id="picture" data-picture data-alt="Casa Romero Mexican website">
        <span data-src="img/casa-romero-mexican.jpg"></span>
        <span data-src="img/casa-romero-mexican@2x.jpg" data-media="(min-device-pixel-ratio: 2.0)"></span>
        <span data-src="img/casa-romero-mexican-md.jpg" data-media="(min-width: 768px") </span> 
// and so on...

The correct img is being loaded and placed on the page, as expected. Here's is a snippet of the generated HTML:

<span data-src="img/casa-romero-mexican-md.jpg" data-media="(min-width: 768px)"><img alt="Casa Romero Mexican website" src="img/casa-romero-mexican-md.jpg"></span>

What I'd like to do is add a class to whichever img tag ends up getting generated.

However, I'm not even able to select the img that is appended! Here's what I'm working with:

alert(($('#picture').children().find('img').size()));

This returns 0, even though the image is on the page. I am expecting it to return a size of 1, b/c based on the media queries, 1 of the images is appended to the page with picturefill.

Just to be sure that there wasn't issues with the DOM loading, I placed picturefill.js in the header (even though JS should go in footer most of the time), and even did this:

$(document).ready(function() {
        alert('ready!');
        alert(($('#picture').children().find('img').size()));
        });

Still doesn't seem to find the img.

È stato utile?

Soluzione

http://learn.jquery.com/using-jquery-core/document-ready/

After reading this, I understood why jQuery was not finding the img. In this case, it was necessary to use $( window ).load(function() { ... }). This will not run the script until the entire page is loaded, as opposed to $( document ).ready(), which only waits for the DOM.

In other words, $( document ).ready() is fine most of the time, but not when waiting on media elements that may take longer to load and/or need to be fetched with a request!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top