Deferring offscreen images is another approach to optimizing the loading of images that are not immediately visible when a user first visits your website. While lazy loading postpones the loading of images until they come into the viewport, deferring offscreen images delays their loading until after the main content of the page has been loaded. This can further improve the perceived performance of your website. Here's how to defer offscreen images:
Use the
defer
Attribute:- The
defer
attribute is used to indicate that a script (or in this case, animg
element) should be executed or loaded after the main content has been parsed. Apply thedefer
attribute to yourimg
elements to defer their loading.
html<img src="image.jpg" alt="Description" defer>
- The
Set the
src
Attribute:- Similar to lazy loading, make sure to provide a
src
attribute with a low-resolution or placeholder image to ensure that some content is displayed while the images are being deferred.
html<img src="placeholder.jpg" data-src="image.jpg" alt="Description" defer>
- Similar to lazy loading, make sure to provide a
Use JavaScript to Swap
src
Attributes:- Use JavaScript to detect when the page's main content has been loaded. Then, swap the
data-src
attribute to thesrc
attribute of theimg
elements to initiate the image loading.
javascript// Wait for the DOMContentLoaded event before swapping src attributes document.addEventListener('DOMContentLoaded', function() { const images = document.querySelectorAll('img[defer]'); images.forEach(img => { img.src = img.dataset.src; img.removeAttribute('data-src'); }); });
- Use JavaScript to detect when the page's main content has been loaded. Then, swap the
Minimize JavaScript Execution:
- The JavaScript snippet should be small and efficient to avoid any delay in the rendering of the rest of the page. Ensure that the JavaScript code does not introduce performance bottlenecks.
Test and Optimize:
- Test your deferring offscreen images implementation across different devices and browsers. Monitor your website's performance to ensure that offscreen images are being deferred and loaded as intended.
Consider Critical Images:
- While deferring offscreen images is effective for improving page load times, be cautious with critical images that are necessary for understanding the content or user interaction. These images should still be loaded in a timely manner.
Deferring offscreen images is a technique that complements other optimization strategies like lazy loading and proper image sizing. Depending on your website's design and content, you can choose the most suitable approach or even combine multiple techniques for optimal performance.
Comments
Post a Comment