Jquery - removing an image before the client browser attempts to download it
I wonder if anyone could help me with a problem I've been having.
I have a number of large images available, but due to space limitations, I can't create multiple copies of these at various sizes. I have used PHP GD functions to resize the images to the sizes I need and output them to the browser. This works, but obviously takes some processing time, which therefore impacts pages load times. I'm fine with this, but I only want to show the image once it's fully loaded, and have a loading gif in its place until that time. I'm using jquery to do this.
The problem I'm having is making the page functional whether the client has javascript enabled or not. If JS is not enabled, I want standard img tags to be outputted, otherwise the images are removed and replaced with a loading gif until they have been fully loaded. The link below shows a sim开发者_StackOverflowple non-javascript unfriendly example of a what I want to do (try turning JS off): http://jqueryfordesigners.com/demo/image-load-demo.php
I've been testing the basics using the code below. The attr() function will be replaced with something like remove(). This is just a test to make something happen to the image before the browser tries to load it.
$(document).ready(function() {
$( "#Thumbnails .thumbnail img" ).attr('src', '#');
});
In IE, this works correctly - the image source is replaced with "#" BEFORE the client browser gets a chance to start downloading the image. In firefox however, it downloads the image, and THEN changes the source. It seems to me that firefox is loading the jquery onready event later than it should. As far as I know, this should be executed before the standard onload event and before anything has started loading. If it helps, I'm testing it with a good number of images on screen (81).
Am I doing something wrong?
I would do the following CSS only solution:
Create a CSS class like this:
preloader {
background: #efefef url(loader.gif) middle center no-repeat;
}
Then for your images simply do this:
<img src="/big file" class="preloader" />
What should result is a background that shows the gif loader up until the point that the image is loaded. If this doesnt work (I have not tested this) then place the IMG inside a div that has the preloader class specified i.e. <div class="preloader"><img /></div>
You could write your image inside a noscript tag that has data-attributes containing your parameters. The contents of noscript are not accessible via script, but the data-src etc. is. This way you have an no js solution and an element to target as needed with the script.
So detect these noscript elements with jquery and add the rotator there. Then swap the rotator when image is loaded.
<noscript data-src="example.jpg">
<img src="example.jpg">
</noscript>
精彩评论