abagshaw abagshaw - 2 months ago 59
CSS Question

Lazy loading img into background not background-image

I am wanting to lazyload an image into the css

tag, not the
tag because I also have a semi-transparent overlay which needs to be applied in the following fashion:

background: linear-gradient(to bottom, rgb(255, 255, 255), rgba(255, 255, 255, 0.60) 75%), url("myimage.jpg") scroll bottom no-repeat;

Currently I am using the jquery.lazy library (https://github.com/eisbehr-/jquery.lazy/) but I'm open to using any lazyloading library as long as it supports fade transitions. How could I accomplish this?

Also, I'm not sure how these plugins work but if they simply overwrite anything in the target tag like simply overwriting what is in the
tag to add the image - that obviously won't work as that will overwrite my semi-transparent overlay.


Answer Source

OP here!

Yes, you can use my jQuery.Lazy plugin for this. But you have to use callbacks to let it work correctly, because this is not a default background image. I made you an full example, it should be pretty easy to understand.

And because you are speaking of fade transitions I think you mean the effect option of this plugin. So I added a fadeIn effect. If you don't want that, just remove effect and effectTime in the options.

$(function() {
        effect: 'fadeIn',
        effectTime: 1000,
        beforeLoad: function(e) {
            // before load, store the gradient onto the element data
            e.data("gradient", e.css("background-image"));
        afterLoad: function(e) {
            // afterwards create the wanted background image
            e.css("background-image", e.data("gradient") + "," + e.css("background-image"));
div {
  width: 600px;
  height: 400px;
  background: linear-gradient(to bottom, rgb(255, 255, 255), rgba(255, 255, 255, 0.60) 75%) scroll bottom no-repeat;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.lazy/1.7.3/jquery.lazy.min.js"></script>

<div data-src="http://dummyimage.com/600x400/000/ff"></div>