300

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

288

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

Sign up to request clarification or add additional context in comments.

12 Comments

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
You might want to think twice about inlining your resources with Data URIs: mobify.com/blog/data-uris-are-slow-on-mobile
The viability of this option depends on which browsers you must support: caniuse.com/datauri
Here's a transparent 1 pixel PNG: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=
Transparent image url that worked for me - data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
|
246

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 Comments

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.
This is causing a broken image icon to display for me. Anyone else seeing this? I'm using the latest Firefox(27).
This also fails w3c validator: Bad value //:0 for attribute src on element img: Invalid host: empty host.
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.
In Firefox 38, this approach triggers the image's onerror handler.
|
98

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 Comments

No HTML error with W3C validator check. No unnecessary request. 👍 Seems to be the valid way how to do it.
Best! One more thing, if you want it to validate in a srcset, use srcset="data:,x"
This causes the image to break in some browsers, displaying the alt text instead of the actual "blank" image.
Yes, the answer says it: "The second example displays 'Alternative Text' (plus broken-image-icon in Chrome and IE)."
As much as I want either of these methods to work, they don't. The image shows a little blob in the top left.
|
22

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 Comments

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.
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.
@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.
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.
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 Comments

+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.
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.
It might also depend on whether there is a fixed width of the container grid. If there is, then there is no reflow
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 Comments

That seems cleaner than letting the network layer issue an error.
At least you're sure a stupid firewall won't ask the permission to call port 0...
It's worth mentioning that this displays the 'broken image' icon on Chrome (and probably other browsers too)
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.
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)
|
13

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 Comments

This will be displayed as a black dot in some browsers.
IE8 for sure, and older versions of Firefox according to stackoverflow.com/questions/9126105/…
this src data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== worked though
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 Comments

[ng-src=''] { visibility: hidden; } if you are using ng-src directive in angularjs
Note, that the src must be set to '', it must not be undefined.
If i'm not mistaken, a request will still be performed
BRAVA great answer!! Words perfect. I add a height of 20px and width 98% as well
12

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 Comments

Are there any arguments against this approach? How is it across browsers?
I've seen both Firefox and Chrome make a second request when using this approach, so I wouldn't recommend it.
Firefox, Chrome make a second request, even JMeter parses the img src, which results in recursive page loads (until maximum depth is reached)
In FF you must hit the Browsers back button twice if you want to leaf the page because the url changes mysteriously..
This is plain wrong. Any who happen to read comments - DO NOT USE THIS
|
11

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 Comments

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.
does not work - shows the broken image icon
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 Comment

It validates, but it results in broken image in Firefox, even with an empty alt attribute.
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 Comments

@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.
All the above solutions are very silly the one accepted included, I'll make a new reply once I get some more time.
@mystrdat: I would be still be happy to learn what you have to say about this?
@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.
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.

Comments

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 Comments

This is nice, but will break if the site packs off.
Agreed, not a reliable long term solution.
-4

Simply, Like this:

<img id="give_me_src"/>

2 Comments

Not a good idea according to the spec: The src attribute must be present, and must contain a valid URL ...
Maybe it works well in chrome, but it WILL throw errors in html validation and it's not a W3 valid html...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.