I have been looking into Preloading images with JQuery and came across this Preloading images with jQuery
Now can someone tell me, do I have to call the preloaded images in any way? I assume this creates a img and then the browser has it cached (at least for that page) and I just use the preloaded image by it's URI?
Can someone clarify here?
Preloading an image can be done with a simple line of JavaScript:
new Image().src='image.png';
For preloading JavaScript files, use the JavaScript include_DOM technique and create a new
<script>
tag, like so:
var js = document.createElement('script'); js.src = 'mysftuff.js';
document.getElementsByTagName('head')[0].appendChild(js);
Here’s the CSS version:
var css = document.createElement('link');
css.href = 'mystyle.css';
css.rel = 'stylesheet';
document.getElementsByTagName('head')[0].appendChild(css);
In the first example, the image is requested but never used, so it doesn’t affect the current page. In the second example, the script is added to the page, so as well as being downloaded, it will be parsed and executed. The same goes for the CSS — it, too, will be applied to the page. If this is undesirable, you can still pre-load the assets using XMLHttpRequest.
For complete tutorial on, "making your website superfast" please visit the following link which i hand picked from many websites and blogs
Preloading images with jQuery
Provided that the server sets correct cache headers, the image should be cached and you should be able to just use the URL and get the image instantly.
You can preload all your images using this below:
function loadImages(){
var images = [
'http://cdn.yourdomain.com/img/image1.png',
'http://cdn.yourdomain.com/img/image2.jpg',
'http://cdn.yourdomain.com/img/image3.jpg',
'http://cdn.yourdomain.com/img/image4.jpg'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
}
I preload a lot using CSS only. I don't like the jQuery versions because you have to wait for the library to be loaded first, and if they don't have JS enabled, or jQuery is delayed, they'll have noticeable image change delays on rollover.
If you need a callback when images have finished preloading, use JS/jQuery. Otherwise, use CSS.
This is just one method which uses :before
, so has browser support limitations (< IE8). The good thing about this one is you dont need any extra HTML markup.
HTML
<div class="logo"></div>
CSS
.logo {
background:url(logo-1.png);
}
.logo:before {
content: url(logo-2.png);
width: 0;
height: 0;
visibility: hidden;
}
Another method would be to simply set background images to hidden elements on your page with the images you need to preload.
HTML
<div id="preload-logo-2"></div>
CSS
#preload-logo-2 {
background: url(logo-2.png);
height: 0;
width: 0;
visibility: hidden;
}