Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent images from loading on non-DOM jQuery AJAX parse

Tags:

jquery

dom

ajax

I'm using jQuery ajax request to grab and parse HTML on a secondary page.. Looking at the Network panel of both Chrome and FF, I noticed that it will load the images from there, too -- but only when I load the result using $(data) in the 'success' callback.

The content is NOT loaded into the current page's DOM, so I'm really kind of confused why this is even happening.

But in any case, simply asked, is there a way to prevent this from happening? I need to grab information from the result, but it never hits the main DOM. Will scripts that prevent image loading until view work here, or would that never fire against the loaded element? Note this is for a userscript app, so I don't quite have control over the target HTML.

Thank you!

like image 703
Morgon Avatar asked Jun 26 '11 15:06

Morgon


1 Answers

The reason why this is happening is that as soon as you create an image with a src property, that image is loaded. For instance:

var image = document.createElement('img');
image.src = 'example.png';

The image is immediately loaded by the browser, before it is appended to the DOM. This is actually generally an optimisation. For instance, it can be used to preload images that will be used later on.

Since jQuery builds the HTML string into a DOM structure, it creates img elements in much the same way as the above snippet does. When the image element comes into existence, even before it is appended to the DOM, the file is loaded from the server.

The simplest solution would be to remove all img tags from the HTML before you append it:

html = html.replace(/<img\b[^>]*>/ig, '');

If that isn't an option and you need the img elements, you could rename the src attributes to something else, or remove the attributes if you don't need them.

like image 151
lonesomeday Avatar answered Oct 20 '22 09:10

lonesomeday