Loading CSS background images before normal images?

后端 未结 4 694
抹茶落季
抹茶落季 2021-01-14 09:58

I have a ruby on rails web app, and in some views i have many heavy images( ) to render .The are generated in a Helper.

4条回答
  •  生来不讨喜
    2021-01-14 10:45

    My approach is to lazy load the images using jquery and data- tags. This approach also allows me to choose different images based on device width and spare tablet/mobile users.

    Graphics
    
    
    $lazy = $('img.lazy');
    
    $(window).load(function(){
      // window load will wait for all page elements to load, including css backgrounds
      $lazy.each(function(){
        // run thru each img.lazy on the page. spare the jquery calls by making $this a variable
        $this = $(this);
        // if the window is greater then 800px wide, use data-src, otherwise, use the smaller graphic
        ($(window).width() >= 800) ? $this.attr('src', $this.attr('data-src')) : $this.attr('src', $this.attr('data-smallsrc'));
      });
    });
    

提交回复
热议问题