Loading CSS background images before normal images?

后端 未结 4 652
抹茶落季
抹茶落季 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:39

    We need to assume things because you haven't shared your code.

    Coming to your query, for now you can preload images using jQuery:

    function preload(arrayOfImages) {
        $(arrayOfImages).each(function(){
            $('<img/>')[0].src = this;
            // Alternatively you could use:
            // (new Image()).src = this;
        });
    }
    
    // Usage:
    
    preload([
        'img/imageName.jpg',
        'img/anotherOne.jpg',
        'img/blahblahblah.jpg'
    ]);
    

    This saves the loading time of loading images.

    0 讨论(0)
  • 2021-01-14 10:42

    Use a base64 string.

    Example:

    background-image: url(data:image/png;base64,*CONVERTED IMAGE DATA HERE*);
    
    • without: **
    • online converter: http://webcodertools.com/imagetobase64converter
    • note: I only would suggest this if the image size is not too heavy.
    0 讨论(0)
  • 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.

    <img src="" data-src="/img/graphic-desktop.jpg" data-smallsrc="/img/graphic-smaller.jpg" alt="Graphics" class="lazy" />
    
    <!-- the following would be in your js file -->
    $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'));
      });
    });
    
    0 讨论(0)
  • 2021-01-14 10:49

    Solution: Do not use the img tag.

    1. Create a sprite containing all your images. Load the sprite in your application.html layout once.
    2. Use data uris to transmit the data directly in the html. See http://css-tricks.com/data-uris/
    0 讨论(0)
提交回复
热议问题