Home > OS >  What happens to an img's src after you set it?
What happens to an img's src after you set it?

Time:07-06

I have a function that takes 3 arguments: an image object, and the filenames of 2 images. The idea is that when the user clicks on it, it toggles the image. (This might be modified later to cycle through many images.)

The problem is that when you set the image's src field, it gets changed immediately. For example, I might do this:

image.src = "myimage.png";

And when I check it, I find that it contains the string "http://www.example.com/path/myimage.png". This is making it difficult to check whether it's currently showing image A or image B. What is the process that the browser goes through to modify this string, and is there a way that I can duplicate it in order to check which image is showing? (I'd rather not modify things to check the tails of the strings, since that would introduce some odd bugs when multiple images happen to have the same tails. It also seems to resolve ..s intelligently, so just concatenating strings is likely a no-go.)

Thanks.

CodePudding user response:

The browser will turn .src into a URL that it can actually fetch. While I don't know if this is the exact mechanism used, you can get similar behavior by using the URL API URL().

You could pre-create a full URL and then set .src to that URL.

const imgSrc = new URL("myimage.png", "https://exmaple.com");
image.src = imgSrc;

Then hold on to imgSrc which will contain the full URL for this image to use for comparison later when checking which image is showing.

CodePudding user response:

The value returned by HTMLImageElement.src is the result of a URL normalization algorithm being applied to source URL. You can approximate this with a relative path using the following method:

const fullSrc = new URL('myimage.png', window.location.href).href;

If you want the raw strings, use Element.setAttribute()/Element.getAttribute():

// Select and store image in variable
const img = document.querySelector('img');

// Store previous attribute value in a variable for subsequent use:
const oldSrc = img.getAttribute('src');

// Set new source attribute value:
img.setAttribute('src', 'myimage.png');

// Use previous value...
  • Related