Reputation: 851
Is there any specific reason we use new Image().src=URL
instead of <img> URL </img>
. I see this kind of usage mostly in web tracking or some image pixels etc. would appreciate your help.
Upvotes: 1
Views: 2365
Reputation: 114481
You can create DOM nodes mainly in two ways:
<img src="foo.jpg">
document.createElement
If the nodes are fixed then static creation is better because allows a designer to create and edit a page directly without having to know Javascript. If however they're created dynamically depending on the user actions on the page then you cannot place them in the HTML and you're forced to use Javascript.
Somethings you may need to just act on an existing DOM element and you may see code like
<img id="pic" src="foo.jpg">
in the HTML (note the id=
part)
and then you can access it from code using for example
document.getElementById("pic").src = "bar.jpg";
Upvotes: 2
Reputation: 337560
This is because the img
tag has an attribute called src
. The HTML in your second example is invalid.
Upvotes: 0