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 t
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]>)*
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.
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