Question

i have a gallery of images and i want assign a class name to all image tag ,that before complete load show preload.gif and when image load complete, show image. i try with this code :

<!DOCTYPE html>
<html>
  <head>
    <script>
      function myFunction() {
        alert("Image loaded: " + document.getElementsById("myImg").complete);
      }
    </script>
  </head>
  <body onload="myFunction()">
    <p>This property returns true if the image is finished loaded, and false if not.</p>
    <img class="myImg" src="compman.gif" alt="Computerman" width="107" height="98">
  </body>
</html>

this code support id name but i want assign class name to all images tag

Was it helpful?

Solution

I finally got it! I tried a few different ways but this way worked best for me.

I have the image originally set to the loading gif, once the gif loads it calls a function to load an image. Once the image is loaded, the function changes the source of the original image from the parameters you send it.

Javascript

function loadimage(imgsrc, change){
  var loadimage = new Image();
  loadimage.onload = changesrc(imgsrc, change);
  loadimage.src = imgsrc;
}

function changesrc(imgsrc, change) {
  change.src=imgsrc;
}

HTML (The photo I link to is large and makes sure you see loading

<img onload="loadimage('http://upload.wikimedia.org/wikipedia/commons/4/49/Swiss_Jungfrau_mountains.jpg',this);" src="http://jimpunk.net/Loading/wp-content/uploads/loading2.gif">

This way lets you set the original image source in the img still, which keeps everything close together.

OTHER TIPS

You can use loading.gif as a background-image for your image CSS class. It has to be either preloaded or base64 data-uri. This way it will show up first for all the images and then real image will load via SRC.

<img class="gal" src="[your image URL]" />

.gal {
    width: 170px;
    height: 104px;
    background-image: url([your loading.gif])
}

Demo: http://jsfiddle.net/ygalanter/bv3Hd/2/

(Note: Clear your browser cache if you want to run the demo again).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top