Wojtek Kochanowski
Wojtek Kochanowski

Reputation: 95

Images being loaded on jquery object creation

I have a string of html, that contains some images. I want to render that html, but without loading the images (there will be a lazy load of sorts here). To achieve this, I create a jquery object from my string and replace the src attributes:

var html = $('<div>').html(string)
html.find('img').attr('src', 'placeholder.jpg')

Problem is, when I look at the contents being loaded on my page, I can see that images are loaded, when I call .html(string). Shouldn't that happen only when I actually put my code into DOM? If not, is there any other way to parse my html and replace src attributes in every <img> tag?

var string = '<div><span>lorem ipsum</span><img src="http://placekitten.com/640/480"/></div>'
var html = $('<div>').html(string)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Upvotes: 0

Views: 108

Answers (2)

Deepak Kumar
Deepak Kumar

Reputation: 413

This way you can remove image but i am not sure what you are willing to do yet. if u only want to replace src or u need to remove just tag and keep the url of image.

$("img").removeAttr("src");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span>lorem ipsum</span>
  <img src="http://placekitten.com/640/480" width="200" />
</div>

Upvotes: 0

Alex Yokisama
Alex Yokisama

Reputation: 1041

As mentioned here, "If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with ). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML."

So it actually creates a DOM element and that is why it starts to load images. Try using regex on the HTML string to find src attributes before creating jQuery object.

You can try something like (?<=src=)("[\w\.\/]+"). Improve it to fit your requirements.

Upvotes: 1

Related Questions