Ticker

6/recent/ticker-posts

How to enable Lazy-loading images on Blogger website.

 

How to enable Lazy-loading images on Blogger website.

Enabling lazy-loading images on a Blogger website can help improve the loading time of your pages, as images are only loaded when they are in the viewport (visible on the screen) of the user. Here are the steps to enable lazy-loading images on a Blogger website:

  1. Log in to your Blogger account and go to the "Theme" section in the left sidebar.
  2. Click on "Edit HTML" to access the code editor.
  3. Right before the line, add the following code:
  4. <b:if cond='data:blog.pageType == &quot;item&quot;'>
      <script type='text/javascript'>
        // Lazy-load images
        document.addEventListener('DOMContentLoaded', function() {
          var lazyImages = [].slice.call(document.querySelectorAll('img[data-src]'));
          if ('IntersectionObserver' in window) {
            let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
              entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                  let lazyImage = entry.target;
                  lazyImage.src = lazyImage.dataset.src;
                  lazyImage.removeAttribute('data-src');
                  lazyImageObserver.unobserve(lazyImage);
                }
              });
            });
            lazyImages.forEach(function(lazyImage) {
              lazyImageObserver.observe(lazyImage);
            });
          } else {
            // Fallback for browsers without IntersectionObserver
            lazyImages.forEach(function(lazyImage) {
              lazyImage.src = lazyImage.dataset.src;
              lazyImage.removeAttribute('data-src');
            });
          }
        });
      </script>
    </b:if>
    

  5. Save the changes and view your blog to confirm that lazy-loading images are now enabled.
Note: This code uses the Intersection Observer API to detect when an image is in the viewport. If the browser does not support this API, a fallback mechanism is used instead. Also, please make sure to back up your theme before making any changes to the code.

Post a Comment

0 Comments