开发者

Prevent images from loading on non-DOM jQuery AJAX parse

I'开发者_StackOverflow社区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!


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.


You can find and delete all the image tags from the returned string before loading it to your DOM.

This is the regex for HTML images:

<[iI][mM][gG][a-zA-Z0-9\s=".]*((src)=\s*(?:"([^"]*)"|'[^']*'))[a-zA-Z0-9\s=".]*/*>(?:</[iI][mM][gG]>)*


Your problem is loading the response text into a jQuery element ($(data)). This actually creates a DOM for the loaded content even though you don't add it to the "main" DOM.

What you should try to do is keep this text out of jQuery and treat it either in the text level using regex, or load it into an XML document and query it with the various XML methods available.

If you want to use jQuery and stop the loading you can try reading here: Javascript: Cancel/Stop Image Requests

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜