简体   繁体   中英

How to get img src in JS if its in svg?

I'm creating online application and I want to figure out in js what source do I have for image - png or svg.

I'm creating img tag:

            var url; //url to icon without extension, like `/img/icon`

            var img = new Image();

            img.crossOrigin = 'Anonymous';
            img.onload = function () {

                //Here I want to know if src was png or svg
            };

            img.onerror = function () {


            };

            img.src = url;

Server serves svg for the url if svg is available OR png if svg is not available.

I can see in network tab when svg is served, so there should be a way to get this info in js as well. Or at least to understand that image was server in svg format.

在此处输入图片说明

How do I know in onload event of Image in which format was source received?

You can get the src onLoad by reference. Then split the string and look for svg at the end.

<img 
  src='www.awesomesite.com/awesomeImage.svg'
  ref={el => this.imageRef = el}
  onLoad={() => console.log(this.imageRef.src) }
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM