Load images before loading any html element

2.3k views Asked by At

I would like to have my background images ready before the HTML loads. But, what is happening is some of my HTML elements like input elements are being loaded before the image is loaded in the background.

I have looked at lot of questions where they show how to preload the image. But, that some how doesn't solve my issue.

2

There are 2 answers

0
dkellner On

You have to delay the loading of the html part. Use any javascript image preloading technique, like this one:

var x=new Image(); 
x.src="whatever.jpg";

...and then, use $.load(...) to load any further html into a div that's initially empty.

0
Deryck On

This is not what you want to do.

For the user this will result in decreased usability and a lack of responsiveness. You'll lose visitors very quickly making them wait for something. Take it the opposite direction and fill in the empty spot with a color while the image loads in the background.

However, if you really want to do this, there is a way to line them all up and load at the same time. You can convert your images to Base64 encoding and paste the code directly into the HTML or CSS.

Here is a very good article on Base64 encoding images and including them inline. Essentially what you'll be doing is turning a picture into text, pasting that text directly in your HTML, JS and/or CSS and then the browser turns it back into an image.

Use your favorite image editor and get your images down to < 32KB, then upload them to this page that will convert it into a long string of characters. If they are larger than 32KB you'll notice browser performance issues as well as incompatibility with Internet Explorer.

You'll take that string of characters and paste it directly where you would normally put the image URL. So if it's in HTML as a standalone image, you would say:

<img src="data:image/png;base64,iVBORw0KGgoAAAA... etc" />

For a CSS image (background-image, for example) it would follow this format:

background-image: url(data:image/png;base64,iVBORw0KGgoAAAA... etc);

Now, depending on how many you include in each file and how large they are, your site will not be very fast to download at first but after caching it won't be a noticeable issue.