Home Avoid large layout shifts DOM elements Skip to main content

Avoid large layout shifts DOM elements

DOM elements contribute CLS of the page. Avoid large layout shifts


Why we have this error:

Ye issue most likely "Cumulative Layout Shift" (CLS) se juda hua hai, jo ek metric hai jo webpage ke elements ke unexpected movement ko measure karta hai jab page load hota hai. Ye movement users ke experience ko kharab kar sakta hai.

"Fix render-blocking fonts by preloading" kehta hai ki fonts jaise important resources jo render-blocking hote hain (page ke load hone mein rukavat banate hain), unhe preloading karke optimize kiya ja sakta hai. Ye issue se juda hua hai kyunki fonts ko load hone mein time lag raha hai aur shayad wo render-blocking hain, jiski wajah se CLS badh raha hai.

Is problem ko solve karne ke liye, aap fonts ko preloading kar sakte hain, taki wo render-blocking na ho aur page ka layout shift na kare. Iske alawa, fonts ki optimization bhi kar sakte hain taki unka loading time kam ho.

Yeh improvements page performance ko enhance karenge aur CLS ko kam karne mein madad karenge, jo ki overall user experience ko behtar banayega.

How to solve this error:

CLS (Cumulative Layout Shift) occurs when elements on a webpage shift visibly as it loads, causing a poor user experience. To fix the CLS issue related to the <div class="all-container">, here are some steps you can take:

Specify Element Dimensions: Ensure that the element (<div class="all-container">) has fixed dimensions (width and height) specified in CSS. This prevents content from shifting as other resources load.

Optimize Images and Media: If the content within this container is images or media, use the correct dimensions in the markup or CSS to reserve space for them. This prevents unexpected shifts when these resources load.

Lazy Loading: Implement lazy loading for images and iframes within the container so that they don't affect the layout until they are about to be viewed.

Font Loading: Regarding the error related to render-blocking fonts, consider preloading the fonts or optimizing font loading to prevent delays in rendering text content.

Minimize JavaScript Execution: Evaluate if any JavaScript is causing layout shifts and try to minimize its impact, either by optimizing its execution or deferring its load until after the initial page render.

Test and Validate Changes: After implementing fixes, use tools like Google PageSpeed Insights or Lighthouse to check if the CLS issue has been resolved. Continuously test to ensure stability across various devices and network conditions.

Always make changes incrementally and test thoroughly to ensure that any adjustments you make don't introduce new issues.

Amazon jaise bade e-commerce sites ki tarah, ek webpage ko optimize karne ke liye alag-alag techniques ko ek sath implement karna important hota hai. Chaliye, ek-ek technique ko samjhte hain:

1. Lazy Loading:

Is technique mein, images, videos, ya heavy content ko load karne mein deri ki jaati hai jab tak wo user ke viewable area mein nahi aata.
Isse initial page load time kam hota hai kyun ki sabhi content ek saath load nahi hota.
Users ko content ko scroll karte waqt tab tak dekhte hain jab tak wo screen par nahi aata.
2. Pagination:

Large data sets ko multiple pages mein divide karna, jisse ek hi page par zyada content na ho.
Users ko navigation ke through pages switch karne ka option milta hai.
Isse server load kam hota hai aur users ko specific pages par jaane ka option milta hai.
3. Caching:

Frequently accessed data ko temporary storage mein save karke future requests ke liye use karna.
Isse server load reduce hota hai aur faster response times milti hain.
4. Optimized Markup:

HTML, CSS, aur JavaScript ka efficient use karna, redundant code se bachna, aur minimal design maintain karna.
Lightweight code se faster loading hota hai aur better user experience milti hai.
5. Asynchronous Loading:

JavaScript aur content ko asynchronous tareeke se load karna.
Isse page rendering ko block nahi kiya jaata aur overall performance improve hoti hai.
In techniques ko combine karke, ek webpage ki performance improve ki ja sakti hai, jisse users ko better experience mile aur server load bhi kam ho. Agar aapko kisi specific technique ke baare mein aur details chahiye ho, toh mujhe bata sakte hain


1. Lazy Loading:


Lazy loading ka concept primarily images, videos, aur other multimedia content ke liye use hota hai jisse initial page load time kam ho. Yeh user ke viewable area ke bahar ke content ko initially load nahi karta, balki jab tak user scroll karta hai tab tak wo content load hota hai.


Blogger platform par aap HTML/JavaScript widgets ka istemal karke is tarah ke code ko apne blog me integrate kar sakte hain. Yahan main aapko step-by-step guide karunga: Blogger Dashboard Open Kare: Blogger ke dashboard mein login karein. Layout Section Mein Jayein: "Theme" section mein jaye. "Edit HTML" ya "Theme" mein jaye, agar aapko HTML/JavaScript widget add karna hai. Code Add Kare: <head> tag ke andar <style> section mein aapki CSS code add karein. <body> ke andar aapka HTML code paste karein. <script> tag ko <body> ke end mein paste karna hoga, sabse last mein. Jab aap code paste karenge, aapko <img> tags ke data-src attribute ko apne actual image URLs se replace karna hoga. Yeh URLs woh honge jo aapko load karni hai. Save Changes: Changes karne ke baad, "Save" ya "Save Theme" par click karein. Yeh aapko lazy loading ka functionality dega aapke Blogger blog mein. Yaad rahe, kuch themes ya restrictions ke chalte, JavaScript widgets ko add karne mein limitations ho sakti hain. Agar koi error aata hai ya widget properly work nahi karta, toh aapko kuch trial and error karke dekhna padega ya phir kisi developer ya Blogger support se help leni hogi.

Yeh ek basic example hai jisme images ko lazy load kiya gaya hai:

HTML
<!DOCTYPE html>
<html>
<head>
  <title>Lazy Loading Example</title>
  <style>
    img {
      width: 300px;
      height: auto;
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <h1>Lazy Loading Example</h1>

  <img data-src="image1.jpg" class="lazyload" alt="Image 1">
  <img data-src="image2.jpg" class="lazyload" alt="Image 2">
  <img data-src="image3.jpg" class="lazyload" alt="Image 3">
  
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      let lazyImages = [].slice.call(document.querySelectorAll(".lazyload"));

      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.classList.remove("lazyload");
              lazyImageObserver.unobserve(lazyImage);
            }
          });
        });

        lazyImages.forEach(function(lazyImage) {
          lazyImageObserver.observe(lazyImage);
        });
      } else {
        // Fallback for browsers that don't support IntersectionObserver
        // Load all images immediately
        lazyImages.forEach(function(lazyImage) {
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.classList.remove("lazyload");
        });
      }
    });
  </script>
</body>
</html>

IF this upper 👆code doesn't save in your theme use down👇 code for this update version


HTML2
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Lazy Loading Example&lt;/title&gt;
  &lt;style&gt;
    img {
      width: 300px;
      height: auto;
      margin-bottom: 10px;
    }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Lazy Loading Example&lt;/h1&gt;

  &lt;img data-src=&quot;image1.jpg&quot; class=&quot;lazyload&quot; alt=&quot;Image 1&quot;&gt;
  &lt;img data-src=&quot;image2.jpg&quot; class=&quot;lazyload&quot; alt=&quot;Image 2&quot;&gt;
  &lt;img data-src=&quot;image3.jpg&quot; class=&quot;lazyload&quot; alt=&quot;Image 3&quot;&gt;
  
  &lt;script&gt;
    document.addEventListener(&quot;DOMContentLoaded&quot;, function() {
      let lazyImages = [].slice.call(document.querySelectorAll(&quot;.lazyload&quot;));

      if (&quot;IntersectionObserver&quot; 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.classList.remove(&quot;lazyload&quot;);
              lazyImageObserver.unobserve(lazyImage);
            }
          });
        });

        lazyImages.forEach(function(lazyImage) {
          lazyImageObserver.observe(lazyImage);
        });
      } else {
        // Fallback for browsers that don&#39;t support IntersectionObserver
        // Load all images immediately
        lazyImages.forEach(function(lazyImage) {
          lazyImage.src = lazyImage.dataset.src;
          lazyImage.classList.remove(&quot;lazyload&quot;);
        });
      }
    });
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;


Lazy loading ka concept primarily images, videos, aur other multimedia content ke liye use hota hai jisse initial page load time kam ho. Yeh user ke viewable area ke bahar ke content ko initially load nahi karta, balki jab tak user scroll karta hai tab tak wo content load hota hai.

Yeh ek basic example hai jisme images ko lazy load kiya gaya hai:});Aap is technique ko other elements jaise videos, audios, text, ya other DOM elements ke liye bhi implement kar sakte hain similar approach se. Aapko sirf un elements ko detect karna hoga jo user ke viewable area mein hain aur jab tak wo scroll hota hai, tab tak hi unko load karna hai.


2. Pagination:

Pagination ek technique hai jisme content ko multiple pages mein divide kiya jata hai, jisse ek hi page par zyada content na ho. Yeh user ko specific pages par jaane ka option deta hai. Main aapko ek example dunga jo images ke saath pagination ko demonstrate karta hai:

<!DOCTYPE html> <html> <head> <title>Pagination Example</title> <style> .gallery { display: flex; flex-wrap: wrap; justify-content: center; } .item { margin: 10px; } .pagination { display: flex; justify-content: center; margin-top: 20px; } .page-link { margin: 0 5px; cursor: pointer; } </style> </head> <body> <h1>Pagination Example</h1> <div class="gallery"></div> <div class="pagination"></div> <script> const itemsPerPage = 6; // Number of items per page const images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg', 'image10.jpg']; const gallery = document.querySelector('.gallery'); const pagination = document.querySelector('.pagination'); function displayImages(pageNumber) { gallery.innerHTML = ''; const startIndex = (pageNumber - 1) * itemsPerPage; const endIndex = startIndex + itemsPerPage; const paginatedImages = images.slice(startIndex, endIndex); paginatedImages.forEach(image => { const imgElement = document.createElement('img'); imgElement.src = image; imgElement.classList.add('item'); gallery.appendChild(imgElement); }); displayPagination(pageNumber); } function displayPagination(currentPage) { pagination.innerHTML = ''; const totalPages = Math.ceil(images.length / itemsPerPage); for (let i = 1; i <= totalPages; i++) { const pageLink = document.createElement('span'); pageLink.textContent = i; pageLink.classList.add('page-link'); if (i === currentPage) { pageLink.classList.add('active'); } pageLink.addEventListener('click', () => displayImages(i)); pagination.appendChild(pageLink); } } // Initial display displayImages(1); </script> </body> </html>

Is code mein, ek gallery structure diya gaya hai jisme images display hoti hain. Pagination ke liye ek div di gayi hai jo page numbers ko display karti hai. JavaScript code items ko pages mein divide karta hai aur pagination ke saath display karta hai. Aap is logic ko apply karke videos, audios, text, ya other DOM elements ke liye bhi pagination implement kar sakte hain.

3. Caching:

Caching ek technique hai jisme frequently accessed data temporary storage mein save kiya jata hai taki future requests ke liye use kiya ja sake. Isse server load reduce hota hai aur faster response times milti hain. Browser side pe, aksar local storage ya session storage ka use hota hai caching ke liye.

Yahaan ek basic example hai jo JavaScript mein local storage ka use karke caching demonstrate karta hai:

<!DOCTYPE html>
<html>
<head>
  <title>Caching Example</title>
</head>
<body>
  <h1>Caching Example</h1>

  <button onclick="getData()">Get Data</button>
  <p id="dataDisplay"></p>

  <script>
    function getData() {
      let cachedData = localStorage.getItem('cachedData');

      if (cachedData) {
        displayData(JSON.parse(cachedData));
      } else {
        // Simulating fetching data from server (you can replace this with actual data fetch logic)
        let dataFromServer = { message: 'This is the fetched data' };
        
        // Save data to cache
        localStorage.setItem('cachedData', JSON.stringify(dataFromServer));
        
        displayData(dataFromServer);
      }
    }

    function displayData(data) {
      document.getElementById('dataDisplay').textContent = data.message;
    }
  </script>
</body>
</html>


Is example mein, localStorage ka use kiya gaya hai jo browser ke local storage ko represent karta hai. getData() function data ko local storage se retrieve karta hai. Agar data local storage mein available hai, toh wo display kiya jata hai, nahi toh server se fetch kiya jaata hai aur fir local storage mein save kiya jaata hai.

Aap is logic ko apne use case ke hisaab se modify karke server se data fetch aur caching ko manage kar sakte hain. Server-side caching bhi hoti hai jahan server cache (RAM ya disk) mein frequently accessed data ko store karke performance improve hoti hai. Server-side caching ke liye aksar CDN aur server-level caching systems ka use hota hai.


4. Optimized Markup:


Optimized Markup ka matalab hai ki aap apne HTML, CSS, aur JavaScript code ko optimize karen taki page load time kam ho, redundant code na ho, aur overall better user experience mile.

Yahaan ek example hai jo optimized markup demonstrate karta hai HTML ke through:


<!DOCTYPE html> <html> <head> <title>Optimized Markup Example</title> <style> /* CSS optimized to target specific elements efficiently */ .main-heading { font-size: 24px; color: #333; } /* Minimalistic CSS without redundancy */ .button { padding: 10px 20px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer; } </style> </head> <body> <!-- Optimized HTML structure --> <h1 class="main-heading">Welcome to Optimized Markup Example</h1> <p>This is a demonstration of optimized markup.</p> <button class="button">Click me</button> <script> // Minimal JavaScript, only necessary functionality document.querySelector('.button').addEventListener('click', function() { alert('Button clicked!'); }); </script> </body> </html>

Is example mein HTML, CSS, aur JavaScript optimized hai:

  1. Optimized HTML: Clean and minimalistic HTML structure without unnecessary elements.
  2. Optimized CSS: CSS rules are specific and avoid redundancy to maintain efficiency.
  3. Minimal JavaScript: Only necessary JavaScript functionality is included.

Optimized markup ke zariye aap page load time ko kam kar sakte hain aur better user experience provide kar sakte hain. Redundant code avoid karke, efficient CSS selectors aur minimalistic JavaScript ka use karke aap markup ko optimize kar sakte hain.


<!DOCTYPE html> <html> <head> <title>Best Practices Example</title> <style> /* Lazy Loading */ .lazyload { opacity: 0; transition: opacity 0.3s ease-in-out; } .lazyloaded { opacity: 1; } /* Pagination */ .gallery { display: flex; flex-wrap: wrap; justify-content: center; } .item { margin: 10px; width: 200px; height: 200px; background-color: #eee; } .pagination { display: flex; justify-content: center; margin-top: 20px; } .page-link { margin: 0 5px; cursor: pointer; } </style> </head> <body> <h1>Best Practices Example</h1> <!-- Lazy Loading Images --> <div class="gallery"></div> <div class="pagination"></div> <script> // Lazy Loading Images const itemsPerPage = 6; const images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg', 'image10.jpg']; const gallery = document.querySelector('.gallery'); const pagination = document.querySelector('.pagination'); function displayImages(pageNumber) { gallery.innerHTML = ''; const startIndex = (pageNumber - 1) * itemsPerPage; const endIndex = startIndex + itemsPerPage; const paginatedImages = images.slice(startIndex, endIndex); paginatedImages.forEach(image => { const imgElement = new Image(); imgElement.dataset.src = image; imgElement.classList.add('item', 'lazyload'); imgElement.onload = function() { imgElement.classList.add('lazyloaded'); }; gallery.appendChild(imgElement); }); displayPagination(pageNumber); } function displayPagination(currentPage) { pagination.innerHTML = ''; const totalPages = Math.ceil(images.length / itemsPerPage); for (let i = 1; i <= totalPages; i++) { const pageLink = document.createElement('span'); pageLink.textContent = i; pageLink.classList.add('page-link'); if (i === currentPage) { pageLink.classList.add('active'); } pageLink.addEventListener('click', () => displayImages(i)); pagination.appendChild(pageLink); } } // Initial display displayImages(1); </script> <!-- Caching --> <script> document.addEventListener('DOMContentLoaded', () => { const cachedData = localStorage.getItem('cachedData'); if (cachedData) { console.log('Data retrieved from cache:', cachedData); } else { const dataFromServer = { message: 'This is the fetched data' }; localStorage.setItem('cachedData', JSON.stringify(dataFromServer)); console.log('Data fetched from server and cached:', dataFromServer); } }); </script> </body> </html>



Yeh code lazy loading for images, pagination for gallery display, aur caching for data storage ke liye ek sample approach ko demonstrate karta hai. Isme images lazy load hoti hain, gallery ko multiple pages mein divide kiya jata hai, aur data local storage mein cache kiya jata hai. Aap is logic ko videos, audios, text, ya other DOM elements ke liye bhi implement kar sakte hain.


5. Asynchronous Loading:

Asynchronous Loading ek technique hai jisme content, assets, ya resources ko asynchronously load kiya jata hai taki page rendering ko block na kiya jaaye aur overall performance improve ho. Yeh JavaScript aur resources ko parallel tareeke se load karke faster user experience provide karta hai.

Yahaan ek example hai jo JavaScript files ko asynchronous tareeke se load karta hai:


<!DOCTYPE html> <html> <head> <title>Asynchronous Loading Example</title> </head> <body> <h1>Asynchronous Loading Example</h1> <script> function loadScript(src, callback) { let script = document.createElement('script'); script.src = src; script.async = true; // Asynchronous loading script.onload = callback; document.head.appendChild(script); } loadScript('your-script-1.js', function() { console.log('Script 1 loaded'); loadScript('your-script-2.js', function() { console.log('Script 2 loaded'); // Add more scripts if needed }); }); </script> </body> </html>

Is code mein loadScript() function ek script ko dynamically create karta hai, async attribute ke saath, jo asynchronous loading ko enable karta hai. Phir callback function ke through script load hone ke baad specific actions perform kiye ja sakte hain.

Aap is technique ko multiple scripts ya other resources ke liye bhi implement kar sakte hain jaise CSS files, images, ya other assets ko asynchronously load karke better performance achieve kar sakte hain.

Comments

Lazy Loading Example Preloaded Image Another Preloaded Image