I have a hidden contact form which is deployed clicking on a button. Its fields are set as CSS background images, and they always appears a bit later than the div that have been toggled.
I was using this snippet in the <head>
section, but with no luck (after I cleared the cache) :
<script>
$(document).ready(function() {
pic = new Image();
pic2 = new Image();
pic3 = new Image();
pic.src="<?php bloginfo('template_directory'); ?>/images/inputs/input1.png";
pic2.src="<?php bloginfo('template_directory'); ?>/images/inputs/input2.png";
pic3.src="<?php bloginfo('template_directory'); ?>/images/inputs/input3.png";
});
</script>
I'm using jQuery as my library, and it would be cool if I could use it as well for arranging this issue.
Thanks for your thoughs.
The only way is to Base64 encode the image and place it inside the HTML code so that it doesn't need to contact the server to download the image.
This will encode an image from url so you can copy the image file code and insert it in your page like so...
If you're reusing these bg images anywhere else on your site for form inputs, you probably want to use an image sprite. That way you can centrally manage your images (instead of having pic1, pic2, pic3, etc...).
Sprites are generally faster for the client, since they are only requesting one (albeit slightly larger) file from the server instead of multiple files. See SO article for more benefits:
CSS image sprites
Then again, this might not be helpful at all if you're just using these for one form and you really only want to load them if the user requests the contact form...might make sense though.
http://www.alistapart.com/articles/sprites
If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)
I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.
Here's a test : http://paragraphe.org/slidetoggletest/test.html
Preloading images using CSS only
Demo
it's better to use a sprite image to reduce http requests...
(if there are many relatively small sized images)
try with this:
With this code you preload the background image and render the form when it's loaded