preload hidden CSS images

后端 未结 5 1194
悲&欢浪女
悲&欢浪女 2020-12-14 11:08

I\'m working on a jquery based homepage with 5 or so hidden divs, each containing several background css images.

The issue is that the browser doesn\'t load css ima

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 11:34

    "This solution seems to load the image into the dom twice...once when the js loads it, and then again when the div layer that loads it becomes visible...so it makes 2 http calls, thus not working"

    The second http request should respond in a 304 (not modified), so I guess that's ok? Another options is to load the image via jQuery and then insert as background image inline via DOM, like:

    jQuery.fn.insertPreload = function(src) {
        return this.each(function() {
            var $this = $(this);
            $(new Image()).load(function(e) {
                $this.css('backgroundImage','url('+src+')');
            }).attr('src',src);
        });
    };
    
    $('div').insertPreload('[huge image source]');
    

提交回复
热议问题