I want to change the image when clicking.

var view = 5; var url = '/images/'+view+'.jpg?'+random; $('#popup').find('img').attr('src', url); 

The problem is that the url of the image is replaced immediately, and the browser updates the image only after a few seconds. How to make an image immediately on click. It is possible to insert a loader somehow, and wait for the image to load.

    2 answers 2

    You can try this:

    First, you need to pre-load the spinner so that it does not flicker.

     (new Image()).src = '/path/to/spinner.gif'; 

    Secondly, set a class for images loading with a spinner

     img.loading { background: transparent url(/path/to/spinner.gif) no-repeat scroll center center; } 

    Finally install it for the desired images.

     <img src="/path/to/real/image.jpg" class="loading"> 

    When the image is loaded, it simply overlaps the background with the spinner.

    • no, it is not known - user2244523
    • Corrected the answer. - Sergey Gornostaev
    • New problem. If src pictures change, then in the code it changes quickly, but the browser does not have time. - user2244523

    Judging by the code, you do not know the pictures that you ship, if they were known, it is better to use sprites, they will kill two birds with one stone - there will be no loading waiting time, and also reduce the traffic load.

    I suggest you to upload a picture when clicked, to display a popup after full download. For example:

     $('#popup').on('click', function(){ $.get('url', function(){ //load image }).done(function(){ //show popup }); });