DEV Community

Seppe Gadeyne
Seppe Gadeyne

Posted on Edited on

Unlocking your website's potential: eliminate render-blocking resources

Do you keep seeing poor Lighthouse scores in Google PageSpeed Insights? The cause is often render-blocking resources. This post shows a few straightforward steps to remove them.

Optimize JavaScript loading to prevent page load delays

A simple change can improve your page's performance: load scripts so that they no longer block the first render. Eliminating render-blocking works here through dynamic injection: the script element is created and appended with JavaScript, so the parser does not wait for it. Scripts added this way are async by default, so script.async = true is not strictly needed, but it makes the intent clear. The Promise does not prevent blocking. It only lets you run code after the script has loaded. Some scripts, like chat widgets, are introduced toward the end of the page or when the user interacts with the website.

Here's an example of how to optimally load Google Tag Manager:

<script type="module">
    // Function to load JavaScript to the DOM
    function loadJS(src, id) {
        return new Promise((resolve) => {
            const script = document.createElement('script')
            script.type = 'text/javascript'
            script.async = true
            script.src = src
            script.id = id
            script.onload = resolve
            document.head.appendChild(script)
        })
    }

    // Load Google Tag Manager 
    loadJS(`https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXXX`, 'gtm').then(() => {
        window.dataLayer = window.dataLayer || []
        window.dataLayer.push({
            event: 'gtm.js',
            'gtm.start': new Date().getTime(),
            'gtm.uniqueEventId': 0
        })
        window.dataLayer.push({ event: 'pageLoad' })
    })
</script>
Enter fullscreen mode Exit fullscreen mode

The following example demonstrates how to load a chat widget only when the user begins scrolling on the website:

<script type="module">
    // Function to load JavaScript to the DOM
    function loadJS(src, id) {
        return new Promise((resolve) => {
            const script = document.createElement('script')
            script.type = 'text/javascript'
            script.async = true
            script.src = src
            script.id = id
            script.onload = resolve
            document.head.appendChild(script)
        })
    }

    function handleScroll() {
      // Load the external JavaScript
      loadJS(`https://static.chatbotkit.com/integrations/widget/v2.js`, 'chatbotkit')

      // Remove the event listener after executing the code
      window.removeEventListener('scroll', handleScroll);
    }

    window.addEventListener('scroll', handleScroll);
</script>
Enter fullscreen mode Exit fullscreen mode

Embedding videos without hindering page load

Adding multimedia, like videos, can provide a rich experience for your users. However, loading external resources such as videos can significantly slow page load time. A solution to this is to initially display a thumbnail of the video and only load the video when the user expresses interest by clicking on the thumbnail.

I applied this technique for a client on their page: Hire silent disco at Verhuurwinkel.nl. It worked seamlessly, ensuring the page loaded faster and providing interactive video content.

Here’s how you can implement this technique for a YouTube video:

<div id="my-youtube-id">
    <button id="my-thumbnail-id" type="button" aria-label="Play video: title of your video" style="border: 0; padding: 0; background: none; cursor: pointer;">
        <img src="https://example.com/images/thumbnail.jpg" alt="" width="1200" height="675">
    </button>
</div>

<script>
    // Function to handle thumbnail click event
    function handleThumbnailClick() {
        const iframe = document.createElement('iframe');
        iframe.setAttribute('title', 'YouTube video player');
        iframe.setAttribute('src', 'https://www.youtube.com/embed/X4z0ojfdLac');
        iframe.setAttribute('width', '1200');
        iframe.setAttribute('height', '675');
        iframe.style.border = '0';
        iframe.setAttribute('allowfullscreen', 'allowfullscreen');

        const contentDiv = document.getElementById('my-youtube-id');
        const thumbnail = document.getElementById('my-thumbnail-id');

        // Replace the image with the iframe
        contentDiv.removeChild(thumbnail);
        contentDiv.appendChild(iframe);
    }

    // Wait for DOM to be ready
    document.addEventListener('DOMContentLoaded', function () {
        const thumbnail = document.getElementById('my-thumbnail-id');
        thumbnail.addEventListener('click', handleThumbnailClick);
    });
</script>
Enter fullscreen mode Exit fullscreen mode

In the code above, a thumbnail image inside a button is initially displayed on the webpage. When the user clicks on the thumbnail, a handleThumbnailClick function is triggered, which replaces the thumbnail with the actual YouTube video iframe. This way, the external video resource is only loaded when it's needed, which helps in reducing the initial load time of your webpage.

By following the above method, you can embed videos in your website without negatively impacting the page load time, further unlocking your website's potential for speed and performance.

Conclusion

With the steps in this post, you can eliminate render-blocking resources from your website and improve its overall website performance. Try them and measure the result in PageSpeed Insights.

Top comments (2)

Collapse
 
vtuz profile image
Valeriy •

Hi, I'm impressed! Visited your website and checked it via pagespeed. To be honest, I've never seen complete 100% in real websites. But then I checked how you include gtag manager and do not see it. Don't you use it as a metric?
Thanks.

Collapse
 
seppegadeyne profile image
Seppe Gadeyne •

Hi @vtuz, Thanks for your feedback! I am using Plausible as a metric and loading this the same way as I described in the tutorial. :-) In other setups, I have been using a tag manager. In those cases, I fire the tag only after the cookie banner is accepted.