简体   繁体   中英

How does a missing src attribute in an img tag behave across browsers?

I have a page with many images hidden inside a set of disclosures. When you click on the title of the section, the image (as well as other things) appears. So far so good. However, there are many of these images, which leads to ridiculous loading times, so I want to load them only when they need to be displayed. When I open the section, I check whether the src of the image is set, and if it isn't, I set it and the image loads. I have found, however, that if I omit the src attribute of my <img> , Javascript (in Chrome) considers it === '' . It's identical to the empty string! I would have expected it to be undefined .

This is pretty nice, but it seems a bit too nice. How do different browsers evaluate img.src when img is an <img> tag without a src ? If I check that img.src === '' , is this safe on other browsers?

You can simply check it like this:

if (!img.src) {
    // need to set the .src property here
}

Since this checks for any falsey value, this will cover you no matter whether the browser returns null , undefined or "" .

FYI, I tried this jsFiddle in Firefox, Chrome and IE and they all returned the empty string for the .src property, but checking for any falsey value as above will make your code more permissible if some older version of some browser has a slightly different idea.

For all the modern browsers, an image with no SRC is complete. But, according to IE, an image with no SRC is not complete - is not loaded . You could use getAttribute() to check if src attribute exists. Like:

if( !img.getAttribute('src') ) {
    //the img does not have src attribute
}

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