dkern / jquery.lazy

A lightweight, fast, feature-rich, powerful and highly configurable delayed content, image and background lazy loading plugin for jQuery & Zepto.
http://jquery.eisbehr.de/lazy
Other
1.02k stars 236 forks source link

pseudo elements #238

Closed palanivelayudam closed 4 years ago

palanivelayudam commented 4 years ago

Hai, i am using images in the pseudo elements somewhere it was necessary, how to add lazy loading for the pseudo elements ? https://www.screencast.com/t/1dMo4tG2dAMH

dkern commented 4 years ago

The short answer is: You can't manipulate pseudo elements with javascript at all! There is no way, with no tool. So therefor you can't use lazy directly to manipulate these.

But there is a workaround: You can create custom css entries at the runtime. So you could add more :after classes dynamically. With that in mind, you could create a custom loader for lazy, and let this create these rules. The only thing you need is a uniqe identifier of the elements. I used guid for this example:

<div data-loader="pseudoLoader" data-after-src="https://dummyimage.com/282x125/000/fff"></div>
jQuery($ => {
  $('div').Lazy({
    pseudoLoader: (element, response) => {
      // create a uniqe identifier of the element
      // if your elements already have a uniqe id, you can use that one too
      let guid = 'lazy_' + createGuid();
      element.attr('id', guid);

      // create a new css entry in cour browsers style sheets
      // adding the provided image as background
      document.styleSheets[0].addRule('#' + guid +'::after','background-image: url(' + element.data('after-src') + ');');
      response(true);
    }
  });
});

// http://guid.us/GUID/JavaScript
function createGuid() {  
  function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);  
  }  

  return (S4() + S4() + "_" + S4() + "-4" + S4().substr(0,3) + "_" + S4() + "_" + S4() + S4() + S4()).toLowerCase();  
}  

Working example.