Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent loading of images in a jQuery objectified HTML fragment

I have a HTML fragment that I'm objectifying via jQuery for the purpose of extracting some data from it. This fragment has some image resources that I don't want the browser to download. Is there a way to do it.

A simplified version of my current code:

var html = '<p class="data">Blah Blah</p>...<img src="/a/b/...png">...<div>...</div>';

var obj = $(html); // this makes the browser download the contained images as well!!!

var myData = {
    item_1: obj.find('.data:first').text(),
    item_2: obj.find('.data2:first').text(),
    .... // and so on..
};
like image 895
techfoobar Avatar asked Apr 02 '13 09:04

techfoobar


1 Answers

Unless you think there will be instances of the substring src= in the string that matter to you, you could do:

html = html.replace(/src=/g, "data-src=");

or possibly

html = html.replace(/src\s*=/g, "data-src=");

...to allow for whitespace. That way, the browser won't see the src attribute, and won't trigger the download.

Sometimes the direct approach is best. Of course, if you think there may be src= substrings that will matter in terms of what you're trying to extract, then...

like image 176
T.J. Crowder Avatar answered Oct 14 '22 08:10

T.J. Crowder