1

I'm trying to prevent out of view images from loading straight away. I've found what seems to be an accepted that involves putting the image src in another attribute then moving this into the src attribute when the image is required to load.

I'm inserting some images in javascript

'<img src="img/grey.png" data-original="'+image.src+'" />'

In Chrome DevTools however I can see the images being loaded (before I've even implemented the code to load them).

Chrome DevTools Resources Tab Chrome DevTools Network Tab Code

Why is this and how can I avoid them being loaded entirely?

I'm running with cache disabled.

More Details:

The images are coming from RSS feeds loaded by Google Feeds API.

feedpointer.load( function (result) {
    if ( !result.error ) {
        $.each( result.feed.entries, function (e, val) {
            tempContent = $( '<div>' + val.content + '</div>' );
            image = tempContent.find( 'img' );
            $('.col_'+id).html('<img src="img/grey.png" data-original="'+image.src+'" />');
        });
    }
}

That's the gist. I can see with DevTools that the image is absolutely nowhere else on the page. I don't think the Feed API will load them as they're contained in text.

I believe tempContent = $( '<div>' + val.content + '</div>' ); might be the offending code making the images load. Is there an alternative to be able to traverse a string as DOM?

Kallum Burgin
  • 95
  • 1
  • 15
  • Images that are referenced only in a data attribute will not load, so you're doing something else wrong ? – adeneo Sep 29 '13 at 20:33
  • Please show any other relevant code. – Jackson Sep 29 '13 at 20:38
  • possibly relevant: http://stackoverflow.com/questions/5117421/how-to-load-images-dynamically-or-lazily-when-users-scrolls-them-into-view – Brad Christie Sep 29 '13 at 21:06
  • Updated with how images are entering DOM. I can provide the site, if helpful, for further inspection. I've seen LazyLoad, but I'd like to get a barebones solution working before thinking about that. – Kallum Burgin Sep 29 '13 at 21:17
  • Might have found the offending code. When a feed is loaded, each item is made into elements via `tempContent = $( '
    ' + val.content + '
    ' );` How can I work around this?
    – Kallum Burgin Sep 29 '13 at 21:26

1 Answers1

0

You could use a function like this, which may not be perfect, but I think it's good enough:

function hideImgSrc( html ){
  return html.replace(/<img[^>]*?>/gi, function( match ){
    return match.replace(/\bsrc(\s*=\s*['"])/gi, function( match, after ){
      return 'data-original' + after;
    });
  });
}

hideImgSrc('<img src = "hello">') --> "<img data-original = "hello">"
biziclop
  • 13,654
  • 3
  • 45
  • 62