Question

I have a page that has lots of images and other code that would work better if it is lazy loaded.

I have been attempting to do this with the noscript tag but I just noticed that it is not working correctly in IE. It works in every other browser I tested (ff,opera,chrome,safari,etc) so I am a little frustrated.

I am pretty sure at one point or another I actually had this working in IE because I have been using the technique for a little while and I test IE quite frequently... but it isn't working now and everything I google seems to suggest that it never worked.

Here is a simple example to copy and paste that shows what I was attempting:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
  <title>lazy load with noscript</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>  
 </head>
 <body>

  <noscript>
   <div>
    <p>other content here</p>
    <img src="http://www.google.com/images/logos/ps_logo.png" alt="lazy loading image test" />
   </div>
  </noscript>

  <noscript>
   <div>
    <p>other content here 2</p>
    <img src="http://www.google.com/images/logos/ps_logo2.png" alt="lazy loading image test 2" />
   </div>
  </noscript>

  <script type="text/javascript">
   var html = $("noscript:first").text();
   alert(html);
   $("body").append(html);
  </script>

 </body>
</html>

The html used for users with javascript and without javascript is the same. I just use jquery to tab the content to make it easier to view. Since the content is tabbed in javascript it needs to lazy load when a tab opens so it does not take ages to download initially when the page has sizable attachments.

How can I achieve this without outputting the html more than once?

Was it helpful?

Solution

What you need to do is have all the images point to a pixel gif (or png). Write a script that checks if a user has scrolled near an image, and then use Javascript to swap the pixel with the full image.

In scripts I have written, you would have an image tag that looks like:

<img src="pixel.gif" data-img="path-to-full-img.jpg" />

Alternately, you could use a plugin like this. Note: I have not used this plugin before, but it looks like it's all you need.

If you really wanted to get hardcore, you could lazyload your javascript using something like head.js or control.js

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top