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

seppegadeyne

Seppe Gadeyne

Posted on May 8, 2023

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

Do you need help constantly seeing poor Lighthouse ratings from Google PageSpeed Insights? The main issue is often render-blocking resources. In this blog post, I'll walk you through some straightforward steps to eliminate these performance issues and help your website achieve the speed boost it deserves.

Optimize JavaScript loading to prevent page load delays

A simple tweak can impact your website's performance. Optimizing loading ensures no longer render-blocking the initial rendering of your page. Eliminating render-blocking is facilitated through the use of a Promise, which allows scripts to be loaded asynchronously without blocking the rendering of the page, ensuring that they are injected into the page only after the initial HTML document has been fully loaded and parsed. 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">
    <img id="my-thumbnail-id" src="https://example.com/images/thumbnail.jpg" alt="ALT text for your image"
        width="1200" height="675" style="cursor: pointer;">
</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.setAttribute('frameborder', '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, an image thumbnail of the video 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

Following the steps outlined in this blog post, you can eliminate render-blocking resources from your website and enhance its overall website performance. Try these tips, and watch your website's loading time dramatically improve!

💖 💪 🙅 🚩
seppegadeyne
Seppe Gadeyne

Posted on May 8, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related