Skip to content Skip to sidebar Skip to footer

Set Img Src Without Issuing A Request

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. Howev

Solution 1:

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.

Solution 2:

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);
});
<imgid="image"src="https://www.w3.org/2008/site/images/logo-w3c-screen-lg" /><br/><buttonid="srcChange">Change src</button><buttonid="imageLoad">Load image</button>

To test it click on Chnage src button then click on Load image button.

Post a Comment for "Set Img Src Without Issuing A Request"