treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Conditionally loading images - IE8 Problem

  • Hello,

    I am currently using reposnd.js to assist in making my site responsive for legacy browsers but I've come up with what is to me (as in i'm very poor with javascript) a pretty big issue.

    On all modern browsers including IE9 my conditional loading of images for larger screen sizes using matchMedia (all code obtained from the excellent Implementing Responsive Design book - see below) works perfectly but on IE8 I'm left with empty spaces where the images should be loaded. I've spent the past couple of hours looking around for a solution but to be totally honest have ended up in a state of near total confusion.

    I'd really appreciate it if someone would spend me the time to a) recommend a robust solution and b) explain how it should be implemented within my site.

    If it helps here is the code (from the book) that I've been using:

    < div data-src="images/supporting-project1.jpg" class="support">
    
      </div>
      <div data-src="images/supporting-project2.jpg" class="support">
    
      </div>
    

    and the javascript

    window.onload = function() {
    
      //images enhancement
      if (window.matchMedia("(min-width: 46.875em)").matches) {
        //load in the images
    
        var lazy = Utils.q('[data-src]');
        for (var i = 0; i < lazy.length; i++) {
          var source = lazy[i].getAttribute('data-src');
          //create the image
          var img = new Image();
          img.src = source;
          //insert it inside of the link
          lazy[i].insertBefore(img, lazy[i].firstChild);
          $('.support img')
            .removeAttr("width").removeAttr("height")
            .css({height: "auto" });
    
    
        };
    

    I Understand that matchMedia is not supported for IE8 hence why this approach fails for this browser.

    Any help could would be much appreciated.

    Regards

    Rob

  • The images are not loaded because that you are actually referring to the images with the data-src. The JavaScript itself creates a img tag with the image when loaded (hitting the matchmedia query).

    What I would recommend is to use the noscript tag and use that as a fallback for old IE:

      <div data-src="images/supporting-project2.jpg" class="support">
      <noscript>
      <img src="images/supporting-project2.jpg" class="support">
      </noscript>
      </div>