As part of building a code to copy and paste, we had to use a dom element that we appended text / other dom elements into it, and in the end the result would be code to copy.
However, when appending image elements, the browser always issues a request for the image src.
Is there any way around it?
i.e.
var img = document.createElement('img');
img.src = 'http://dummy.com';
without the browser firing a request to dummy.com?
The reason I am asking is I have a template, that looks something like this:
<div class="container">
<div class="items-container">
<generated tags here>
</div>
</div>
Where generated tags are with img inside.
I was trying to append the a tags with the image inside and get the HTML so I can give it to the user to use it on their email campaigns.
But I guess it's just not supported.
I ended up adding {{token}} instead of the real html, and then used strings (ugly, but worked)
After some more research, it seems like it's impossible, unless there is a browser API I am missing.
Any new Image tag with src will result in a request going out from the browser, even if it's just in memory, or wrapped in a code block.
You can create HTML5 data-*
custom attribute and do this work. See it in this.
You can store image address in data-address
custom attribute and when you want to load image, get it and set to src
attribute. See my example
var imageSrc = "https://www.w3.org/2008/site/images/w3devcampus.png"
var image = document.getElementById("image");
var srcChange = document.getElementById("srcChange");
var imageLoad = document.getElementById("imageLoad");
srcChange.addEventListener("click", function(){
image.setAttribute("data-address", imageSrc);
});
imageLoad.addEventListener("click", function(){
var src = image.getAttribute("data-address");
image.setAttribute("src", src);
});
<img id="image" src="https://www.w3.org/2008/site/images/logo-w3c-screen-lg" />
<br/>
<button id="srcChange">Change src</button>
<button id="imageLoad">Load image</button>
To test it click on Chnage src
button then click on Load image
button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With