简体   繁体   中英

Getting portions of javascript to fire before entire function(s) finishes

I am changing a image via jQuery, but the image takes a few seconds to load and hence appears like the click did nothing, so I needed to input a temporary "loading" image to show the user that the image is loading.

However as I have experienced in the past JS doesn't really fire things as things happen, it waits until the full function is done before things happen; I recall coming up with a solution in the past but I just can't remember what it was.

I have this which does each task, but the user never sees the loading image because it is replaced by the new image before the user even sees anything.

function changeMainImage(image) {

    // Set temporary loading image
    jQuery('#main_image').attr('src', 'images/loading.jpeg');    

    // Set big image
    var big_image = image + '-big.png'

    // Update main image url
    jQuery('#main_image').attr('src', big_image);

}

I have tried putting the below into a separate function:

// Set temporary loading image
jQuery('#main_image').attr('src', 'images/loading.jpeg');

..and calling it before the other function like so..

onclick="setLoadingIMage(); changeMainImage('images/ai');"

but that didn't change anything.

Could anyone tell me what I need to do to achieve the effect I want?

<label id="label"> Loading </label>
<img src="src" id="image" style="display:none;"/>

JS:

var image = document.getElementById('image');
var label = document.getElementById('label');

image.onload = function(){
    image.style.display = "block";
    label.style.display = "none";
}

Fiddle: http://jsfiddle.net/3x63F/ (the image is too big, so it may take several minutes to load)

This will display the loading.jpeg until the image has been loaded.

function changeMainImage(image) {

    jQuery('#main_image').attr('src', 'images/loading.jpeg');

    var img = new Image();
    img.src = image + "-big.png";

    img.onload = function( ) {
          jQuery('#main_image').attr('src', img.src );
    }
}

If the image is held in cache then img.onload will fire immediately.

Demo here

Here is a trick I use for this:

  1. Embed image in a div
  2. Keep a loading image as a background of the Div
  3. When the image is loaded, it is displayed hiding the loading background behind.

Hope this works for you. Also, you may choose an animated gif for loading image.

Here is the tutorial of how to accomplish showing the spinner in the foreground while the image is loading in background

Image Loading Spinner

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM