291

I have an image that I will dynamically populate with a src later with javascript but for ease I want the image tag to exist at pageload but just not display anything. I know <img src='' /> is invalid so what's the best way to do this?

3
  • 6
    This is a relatively old question, but it's worth considering that an image with no src is essentially meaningless and that is why the spec says that image must have an src pointing to some embedded resource in the first place. If you're thinking about validity and/or semantics, you're much better served by omitting the image entirely and adding it after the fact, since HTML does not provide a way to specify a placeholder image that will be populated with data later.
    – BoltClock
    Commented Feb 16, 2016 at 9:22
  • 1
    In using Mika Tuupola's lazy loading jQuery plugin, it uses markup '<img class="lazy" data-original="img/example.jpg" width="640" height="480">', so in a sense, you need to point to a source, but it does not have to be done with the src attribute. Commented Oct 5, 2016 at 6:51
  • 1
    You can use div element instead of it please see this => stackoverflow.com/a/5513934/1395101 Commented Apr 8, 2018 at 0:17

15 Answers 15

284

Another option is to embed a blank image. Any image that suits your purpose will do, but the following example encodes a GIF that is only 26 bytes - from http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever

<img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" width="0" height="0" alt="" />

Edit based on comment below:

Of course, you must consider your browser support requirements. No support for IE7 or less is notable. http://caniuse.com/datauri

12
  • 23
    Great idea! For me however, this kills the image element - if anyone needs other aspects of the img element to show e.g. background and border, try src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" which is taken from a 1px x 1px transparent gif I made I Photoshop pushed through base64-image.de Commented Aug 28, 2013 at 15:06
  • 4
    You might want to think twice about inlining your resources with Data URIs: mobify.com/blog/data-uris-are-slow-on-mobile
    – shawnjan
    Commented Sep 1, 2013 at 19:08
  • 1
    The viability of this option depends on which browsers you must support: caniuse.com/datauri Commented Nov 6, 2013 at 0:37
  • 10
    Here's a transparent 1 pixel PNG: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=
    – Keavon
    Commented Aug 12, 2014 at 22:21
  • 4
    Transparent image url that worked for me - data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
    – Vikram Rao
    Commented Feb 14, 2017 at 0:23
245

While there is no valid way to omit an image's source, there are sources which won't cause server hits. I recently had a similar issue with iframes and determined //:0 to be the best option. No, really!

Starting with // (omitting the protocol) causes the protocol of the current page to be used, preventing "insecure content" warnings in HTTPS pages. Skipping the host name isn't necessary, but makes it shorter. Finally, a port of :0 ensures that a server request can't be made (it isn't a valid port, according to the spec).

This is the only URL which I found caused no server hits or error messages in any browser. The usual choice — javascript:void(0) — will cause an "insecure content" warning in IE7 if used on a page served via HTTPS. Any other port caused an attempted server connection, even for invalid addresses. (Some browsers would simply make the invalid request and wait for them to time out.)

This was tested in Chrome, Safari 5, FF 3.6, and IE 6/7/8, but I would expect it to work in any browser, as it should be the network layer which kills any attempted request.

7
  • 19
    This answer can cause your firewall to warn you about accessing port 0 for example. Or it could cause a server security log. The answer advising about:blank is probably a better solution. Commented Jan 22, 2013 at 15:47
  • 12
    This is causing a broken image icon to display for me. Anyone else seeing this? I'm using the latest Firefox(27).
    – dmikester1
    Commented Feb 11, 2014 at 20:00
  • 12
    This also fails w3c validator: Bad value //:0 for attribute src on element img: Invalid host: empty host.
    – ysrb
    Commented Aug 7, 2014 at 14:28
  • This doesn't work: I have a ASP.NET MVC 4 application which contains a image gallery plugin called clearing. The plugin creates the images dynamically and it puts the //:0 o the src untill the image is actually fetched. This was making the index action of my homecontroller to be called twice. So beware.
    – jpgrassi
    Commented Sep 11, 2014 at 15:04
  • 3
    In Firefox 38, this approach triggers the image's onerror handler. Commented May 27, 2015 at 19:55
95

These days IMHO the best short, sane & valid way for an empty img src is like this:

<img src="data:," alt>
or
<img src="data:," alt="Alternative Text">

The second example displays "Alternative Text" (plus broken-image-icon in Chrome and IE).

"data:," is a valid URI. An empty media-type defaults to text/plain. So it represents an empty text file and is equivalent to "data:text/plain,"


OT: All browsers understand plain alt. You can omit ="" , it's implicit per HTML spec.

7
  • 9
    No HTML error with W3C validator check. No unnecessary request. 👍 Seems to be the valid way how to do it.
    – Avatar
    Commented May 25, 2019 at 12:48
  • 2
    Best! One more thing, if you want it to validate in a srcset, use srcset="data:,x"
    – lucian
    Commented Nov 13, 2019 at 14:45
  • 2
    This causes the image to break in some browsers, displaying the alt text instead of the actual "blank" image.
    – Ken
    Commented Nov 30, 2020 at 13:08
  • 2
    Yes, the answer says it: "The second example displays 'Alternative Text' (plus broken-image-icon in Chrome and IE)."
    – j.j.
    Commented Nov 30, 2020 at 20:15
  • 1
    As much as I want either of these methods to work, they don't. The image shows a little blob in the top left.
    – jjxtra
    Commented Jan 31, 2023 at 21:01
21

Use a truly blank, valid and highly compatible SVG, based on this article:

src="data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E"

It will default in size to 300x150px as any SVG does, but you can work with that in your img element default styles, as you would possibly need in any case in the practical implementation.

4
  • Thanks for updating your answer, but i suspect compatibility is even worse for this, than the other data-uri solution, given that you use svg which was not compatible until IE9. Fortunately, it's been a while since I had to support legacy IE but it is still relevant to some people.
    – zkwsk
    Commented Jun 7, 2016 at 10:35
  • But doesn't this suffer the same issues as in this article? dev.mobify.com/blog/data-uris-are-slow-on-mobile. I'm thinking the <img src="about:blank"> option with css img[src="about:blank"] {opacity: 0} solution is best. Or, if that level of CSS selector is not supported in older browsers, just give the img tag a class like "load-in", or something. Better yet, give it the class, use JavaScript to swap the data-src, and then set a load function to the image to make it fade in on load. You can also set a spinner to be shown while it's loading. Looks really professional. Commented Sep 17, 2016 at 13:41
  • @JordanCarter Sure, if detailed performance is a concern. As a sidenote, I would say visibility: hidden is a bit more fitting than opacity: 0 for the attribute selectors you're suggesting.
    – zrooda
    Commented Sep 20, 2016 at 10:59
  • 1
    Thank you. This one really helped me. With other solutions I was having issues with maintaining aspect ratio of the placeholder image in different screen sizes. This one works for images of any aspect ratio. Commented Jan 6, 2022 at 18:45
19

I recommend dynamically adding the elements, and if using jQuery or other JavaScript library, it is quite simple:

also look at prepend and append. Otherwise if you have an image tag like that, and you want to make it validate, then you might consider using a dummy image, such as a 1px transparent gif or png.

3
  • 7
    +1 This is the best answer. If the image source is being set dynamically anyway, the entire element should be added dynamically. If you don't want it visible until the src is set, I can't think of any good reason why the element should be there before that. Commented May 19, 2014 at 16:06
  • Dynamically adding the image is generally better, but it adds the problem of changing the layout flow. An empty placeholder of equal size may be needed. Sometimes calculating that placeholder's size can be difficult if elements are auto-sized. In such cases, I find the embedded blank image a better option.
    – pmont
    Commented Feb 5, 2021 at 15:36
  • It might also depend on whether there is a fixed width of the container grid. If there is, then there is no reflow Commented Feb 5, 2021 at 15:38
14

I haven't done this in a while, but I had to go through this same thing once.

<img src="about:blank" alt="" />

Is my favorite - the //:0 one implies that you'll try to make an HTTP/HTTPS connection to the origin server on port zero (the tcpmux port?) - which is probably harmless, but I'd rather not do anyways. Heck, the browser may see the port zero and not even send a request. But I'd still rather it not be specified that way when that's probably not what you mean.

Anyways, the rendering of about:blank is actually very fast in all browsers that I tested. I just threw it into the W3C validator and it didn't complain, so it might even be valid.

Edit: Don't do that; it doesn't work on all browsers (it will show a 'broken image' icon as pointed out in the comments for this answer). Use the <img src='data:... solution below. Or if you don't care about validity, but still want to avoid superfluous requests to your server, you can do <img alt="" /> with no src attribute. But that is INVALID HTML so pick that carefully.

Test Page showing a whole bunch of different methods: http://desk.nu/blank_image.php - served with all kinds of different doctypes and content-types. - as mentioned in the comments below, use Mark Ormston's new test page at: http://memso.com/Test/BlankImage.html

7
  • That seems cleaner than letting the network layer issue an error. Commented Jan 22, 2013 at 15:41
  • 1
    At least you're sure a stupid firewall won't ask the permission to call port 0... Commented Jan 22, 2013 at 15:46
  • 1
    It's worth mentioning that this displays the 'broken image' icon on Chrome (and probably other browsers too) Commented Aug 28, 2013 at 14:58
  • 1
    It's worse than I thought - even with the html5 doctype it doesn't seem to work in Safari or Chrome. I have a test page up that will twiddle the Content-type and Doctype of a page, and so far my favorite is: <img /> - an image tag without the src attribute. This is not valid (so there's no point putting the empty alt tag in there, either). I'm continuing to play with it and will update my answer (or strike-through it) accordingly.
    – Uberbrady
    Commented Aug 31, 2013 at 23:01
  • 2
    I took your test page and updated it so it is far more obvious when images do not work properly. The old blank image is included as an "Always Works" example, as well as a brief description of what you are seeing: memso.com/Test/BlankImage.html This lead me to realize that the valid blank data gif is the only reusable option for modern browsers, other than the old blank gif image (which is still required for old IE7 and below) Commented Jan 24, 2014 at 0:00
13

I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.

[src=''] {
    visibility: hidden;
}
4
  • [ng-src=''] { visibility: hidden; } if you are using ng-src directive in angularjs Commented Jan 31, 2018 at 20:17
  • 3
    Note, that the src must be set to '', it must not be undefined. Commented Aug 30, 2018 at 13:57
  • If i'm not mistaken, a request will still be performed
    – Nico
    Commented Mar 18, 2020 at 9:24
  • BRAVA great answer!! Words perfect. I add a height of 20px and width 98% as well
    – Evan TOder
    Commented Feb 3, 2023 at 5:25
11

As written in comments, this method is wrong.

I didn't find this answer before, but acording to W3 Specs valid empty src tag would be an anchor link #.

Example: src="#", src="#empty"

Page validates successfully and no extra request are made.

7
  • 1
    Are there any arguments against this approach? How is it across browsers?
    – tremby
    Commented Mar 13, 2015 at 19:20
  • 18
    I've seen both Firefox and Chrome make a second request when using this approach, so I wouldn't recommend it.
    – Marius
    Commented Apr 17, 2015 at 14:13
  • 5
    Firefox, Chrome make a second request, even JMeter parses the img src, which results in recursive page loads (until maximum depth is reached)
    – burna
    Commented Apr 27, 2015 at 10:18
  • 1
    In FF you must hit the Browsers back button twice if you want to leaf the page because the url changes mysteriously..
    – Kalaschni
    Commented Jan 25, 2016 at 12:23
  • 3
    This is plain wrong. Any who happen to read comments - DO NOT USE THIS Commented May 22, 2016 at 8:49
10

if you keep src attribute empty browser will sent request to current page url always add 1*1 transparent img in src attribute if dont want any url

src="data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA="
3
  • 2
    This will be displayed as a black dot in some browsers.
    – tomasz86
    Commented Jul 26, 2015 at 18:31
  • IE8 for sure, and older versions of Firefox according to stackoverflow.com/questions/9126105/…
    – tomasz86
    Commented Jul 29, 2015 at 8:57
  • 3
    this src data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== worked though
    – Max Yari
    Commented Nov 25, 2016 at 17:44
10

I've found that using:

<img src="file://null">

will not make a request and validates correctly.

The browsers will simply block the access to the local file system.

But there might be an error displayed in console log in Chrome for example:

Not allowed to load local resource: file://null/
2
  • 4
    Care to explain the downvote? Note that I'm not recommending using this method just providing a case for discussion. And it's satisfying the requirements from the question to validate correctly and to not make additional requests.
    – tenkod
    Commented Aug 28, 2015 at 18:15
  • does not work - shows the broken image icon
    – Evan TOder
    Commented Feb 3, 2023 at 5:25
4

Building off of Ben Blank's answer, the only way that I got this to validate in the w3 validator was like so:

<img src="/./.:0" alt="">`
1
  • It validates, but it results in broken image in Firefox, even with an empty alt attribute. Commented May 30, 2019 at 12:47
3

I personally use an about:blank src and deal with the broken image icon by setting the opacity of the img element to 0.

4
  • @mystrdat: Care to elaborate why it's dirty? The accepted answer, using "//:0" still gave me the broken image icon plus a weird never ending request on Firefox. The single pixel base64 png alternative, also with lots of votes, gave me trouble when using the <img> as placeholder, both with and without specifying the height and width. This is the cleanest way I found to achieve my goal without any unnecessary requests and passing all linters and validations.
    – Miguel
    Commented Feb 12, 2015 at 19:12
  • All the above solutions are very silly the one accepted included, I'll make a new reply once I get some more time.
    – zrooda
    Commented Feb 12, 2015 at 21:17
  • @mystrdat: I would be still be happy to learn what you have to say about this?
    – zkwsk
    Commented May 6, 2016 at 9:19
  • 1
    @funkylaundry I apologize for making big claims and disappearing, posted my answer now. I also admit I haven't noticed the other Data URI solutions before, which I do agree with, but I do believe mine is superior in the syntax anyway.
    – zrooda
    Commented May 26, 2016 at 0:13
2
<img src="invis.gif" />

Where invis.gif is a single pixel transparent gif. This won't break in future browser versions and has been working in legacy browsers since the '90s.

png should work too but in my tests, the gif was 43 bytes and the png was 167 bytes so the gif won.

p.s. don't forget an alt tag, validators like them too.

0

I know this is perhaps not the solution you are looking for, but it may help to show the user the size of the image before hand. Again, I don't fully understand the end goal but this site might help: https://via.placeholder.com

It's stupid easy to use and allows to show the empty image with the needed size. Again, I understand you did not want to show anything, but this might be an elegant solution as well.

 <img src="https://via.placeholder.com/300" style='width: 100%;' />
2
  • This is nice, but will break if the site packs off. Commented Dec 16, 2022 at 4:35
  • Agreed, not a reliable long term solution. Commented Dec 19, 2022 at 18:18
-4

Simply, Like this:

<img id="give_me_src"/>
2
  • 5
    Not a good idea according to the spec: The src attribute must be present, and must contain a valid URL ... Commented Oct 16, 2016 at 19:17
  • 2
    Maybe it works well in chrome, but it WILL throw errors in html validation and it's not a W3 valid html...
    – EhsanT
    Commented Nov 25, 2016 at 12:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.