The image with display none I want it not to load

1

I have a question, I am optimizing a website and in the mobile version I am putting smaller images and therefore I am hiding the desktop image with CSS display none. The problem of mine is that no matter how much you put a display none of the desktop image is still loaded even if you can not see it. In what way can I do so that the desktop image is not loaded in the mobile version but when I enlarge the screen if the desktop version is loaded?

    
asked by Gerardo Fuentes 19.01.2018 в 15:39
source

1 answer

3

You could use javascript to load the image you want, it would look like this:

Suppose you have an image tag like this:

<img id='img_bg'>

Then you attend the event when the screen is resized:

$(function() { 
    reDim() //llamo aquí la función para que compruebe con el onLoad de la pagina las dimensiones cuando se cargue

    $( window ).resize(function() { // cada vez que se re dimensiona la pantalla compruebas en que dimensión esta para cargar la imagen que debe ser
      reDim()
   });

  function reDim(){

     if( window.innerWidth >= 768){
               $('#img_bg').prop('src','/desktop.png')
        }else{

           switch(window.innerWidth) {
               case 600:
                  $('#img_bg').prop('src','/otra1.png')
                  break;
               case 500:
                  $('#img_bg').prop('src','/otra2.png')
                  break;
               case 400:
                  $('#img_bg').prop('src','/otra3.png')
                  break;
               case 300:
                  $('#img_bg').prop('src','/otra4.png')
                  break;
               default:
                  $('#img_bg').prop('src','/otra5.png')
           }
       }

  }
});
  

Note: You must use jquery for the previous code.

    
answered by 19.01.2018 / 15:53
source