Back to home

Optimizing Page Load Speed with async and onload

Ninja Bootstrap Team

July 8, 2024

Join our Discord

In the world of web development, optimizing page load speed is crucial for enhancing user experience and improving search engine rankings.

One effective method is to use the `async` attribute and `onload` event for loading scripts. These attributes help to load scripts asynchronously and execute code once the script is fully loaded, ensuring that the page rendering is not blocked.
Let’s dive into two examples that demonstrate how to use these techniques effectively.

What you see below is the issue that Google’s PageSpeed Insights might flag if you don’t correctly implement RELLAX JavaScript in the way we’re explaining.
As you can see in the diagnostics, under the section “ELIMINATE RENDER-BLOCKING RESOURCES,” there’s an optimization problem that needs to be addressed and resolved.

Resources are blocking the first paint of your page. Consider delivering critical JS/CSS inline and deferring all non-critical JS/styles. Learn how to eliminate render-blocking resources.LCPFCP

Eliminate render-blocking resources

Example 1: Rellax.js Script with Asynchronous Loading

Below, you’ll find the example we’ll build using RELLAX and LiveCanvas.

In this example, we see a section that uses RELLAX, a popular JavaScript library, to create a parallax effect with three divs. These sections have different syntax depending on the speed of the vertical parallax movement.
As you can see, these sections use three different data attributes, RELLAX SPEED, which dictate their behavior. The original code you find on the RELLAX page may cause issues when implemented within a WordPress page.

However, using this technique, you can optimize the page concerning page speed.

we use the `async` attribute to load the Rellax.js library asynchronously. This allows the rest of the page to continue loading without waiting for the script to finish. Once the script is loaded, the `onload` event initializes the Rellax library.

Rellax Code Before optimization

This is the code before optimization that you can find in the instructions on the official RELLAX page.

<script src="https://cdnjs.cloudflare.com/ajax/libs/rellax/1.12.1/rellax.min.js"></script>
<script>
var rellax = new Rellax('.rellax', {
  });
</script>

 

Optimized Rellax Code

Here is the solution we propose to optimize the above code.

<script async="" src="https://cdnjs.cloudflare.com/ajax/libs/rellax/1.12.1/rellax.min.js" onload="new Rellax('.rellax');"></script>

 

Full Code Solution

Here is the entire code for the example, which you can check out at this link to see it in action.

<script async="" src="https://cdnjs.cloudflare.com/ajax/libs/rellax/1.12.1/rellax.min.js" onload="new Rellax('.rellax');"></script>
<section class="min-vh-100 py-10">
	<div class="container-fluid py-10  ">
		<div class="row mb-4 mb-lg-5 justify-content-lg-between">
			<div data-rellax-speed="-3" class="rellax col-3 col-md-1 col-lg-2 d-none d-md-flex align-items-center rellax">
				<div class="lc-block bg-dark ratio ratio-1x1 opacity-25" style=""> </div><!-- /lc-block -->
			</div><!-- /col -->
			<div data-rellax-speed="7" class="rellax col-4 col-md-3 col-lg-2 d-flex flex-column justify-content-between">
				<div class="lc-block bg-primary ratio ratio-1x1 opacity-25" style=""> </div><!-- /lc-block -->
				<div class="lc-block"><img class="  img-fluid" src="https://images.unsplash.com/photo-1531445075774-bfb641f42229?crop=entropy&amp;cs=tinysrgb&amp;fit=crop&amp;fm=webp&amp;ixid=MnwzNzg0fDB8MXxzZWFyY2h8Njd8fGJ1aWxkaW5nfGVufDB8Mnx8fDE2MzQ1NTE3NDg&amp;ixlib=rb-1.2.1&amp;q=80&amp;w=1080&amp;h=1080" alt="Photo by Meriç Dağlı"></div><!-- /lc-block -->
			</div><!-- /col -->
			<div data-rellax-speed="-5" class="rellax col-4 col-md-4 col-lg-3">
				<img class="img-fluid" src="https://images.unsplash.com/photo-1526546334624-2afe5b01088d?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=webp&amp;ixid=MnwzNzg0fDB8MXxzZWFyY2h8MzF8fGJ1aWxkaW5nfGVufDB8MXx8fDE2MzQ1NTE2NTE&amp;ixlib=rb-1.2.1&amp;q=80&amp;w=1080" style="object-fit:cover" alt="Photo by Simone Hutsch">
			</div><!-- /col -->
			<div data-rellax-speed="-7" class="rellax col-4 col-md-3 col-lg-2 d-flex flex-column justify-content-between">
				<div class="lc-block">
					<img class="img-fluid" src="https://images.unsplash.com/photo-1528810084506-41bd091551af?crop=entropy&amp;cs=tinysrgb&amp;fit=crop&amp;fm=webp&amp;ixid=MnwzNzg0fDB8MXxzZWFyY2h8NDJ8fGJ1aWxkaW5nfGVufDB8Mnx8fDE2MzQ1NTE3NDE&amp;ixlib=rb-1.2.1&amp;q=80&amp;w=1080&amp;h=1080" alt="Photo by Simone Hutsch">
				</div><!-- /lc-block -->
				<div class="lc-block bg-primary ratio ratio-1x1 opacity-25" style=""> </div><!-- /lc-block -->
			</div><!-- /col -->
			<div data-rellax-speed="-10" class="rellax col-3 col-md-1 col-lg-2 d-none d-md-flex  align-items-center">
				<div class="lc-block bg-dark ratio ratio-1x1 opacity-25" style=""> </div><!-- /lc-block -->
			</div><!-- /col -->
		</div>
	</div>
	<div class="container position-relative">
		<div class="row justify-content-center">
			<div class="lc-block text-center col-md-8">
				<div editable="rich">
					<h1 class="rfs-25 fw-bold">The quick brown fox jumps over the lazy dog</h1>
				</div>
			</div>
		</div>
		<div class="row justify-content-center">
			<div class="lc-block text-center col-xxl-6 col-md-8">
				<div editable="rich">
					<p class="lead"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc et metus id ligula malesuada placerat sit amet quis enim.</p>
				</div>
			</div><!-- /lc-block -->
		</div>
	</div>
</section>

    

Solved Eliminate render-blocking resources

After correctly implementing the solution shown above, if you run the PageSpeed test again, you should see “PASSED” under the “Eliminate Render-Blocking Resources” section.
This means you’ve successfully resolved the issue.

Example 2: Gsap animation on scroll

Now let’s look at another example. For this one, we’ll see how to implement the GSAP library. GSAP is a library that allows you to animate objects through various interactions, such as scrolling. In this example, we will learn how to call the two JavaScript assets from the CDN: GSAP and ScrollTrigger, which are necessary to start getting animations while scrolling the page. For this example, we used our home page from UI Bootstrap Ninja, where an element, a custom SVG, rotates during scrolling.

In this example, we load the GSAP library and its ScrollTrigger plugin asynchronously. We then use the `onload` event to create a smooth animation for an SVG element based on the scroll position.

Benefits of Using `async` and `onload`

  1. Non-blocking Loading: The `async` attribute allows the script to load in the background without blocking the rendering of the rest of the page. This results in faster initial page loads.
  2. Execution Control: The `onload` event ensures that certain actions are only performed after the script has fully loaded. This is crucial for scripts that depend on the complete loading of libraries or other resources.
  3. Improved Performance: By leveraging `async` and `onload`, you can significantly improve page load times and overall performance, leading to a better user experience and higher search engine rankings.

By implementing these techniques, you can optimize your web pages for faster loading times and smoother interactions, enhancing both user satisfaction and search engine performance.

 

GSAP Code Before optimization

This is the code before the optimization.

<section class="overflow-hidden py-4 py-lg-0 pb-lg-9 position-relative">
	<div class="position-relative mb-6 mb-lg-4 mb-xl-0">
		<img class="position-absolute rotation top-15 top-lg-35 top-xxl-0 start-0 start-xl-15 start-xxl-25 w-100 h-100 z-n1 " src="https://ui.bootstrap.ninja/wp-content/uploads/2024/01/cosmos.svg">
	</div>
</section>

<!-- the other components are intentionally omitted to keep the code readable, Inspect the code of our homepage at https://ui.bootstrap.ninja/ -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/ScrollTrigger.min.js"></script>
<script>
    // Select the SVG with the rotation class
    const svgRotation = document.querySelector('.rotation');

    // Listen for scroll events on the window
    window.addEventListener('scroll', () => {
        // Calculate the rotation based on scroll position
        let scrollPercent = window.scrollY / (document.body.offsetHeight - window.innerHeight);
        let rotationDegrees = scrollPercent * 270; // Reduced speed by changing 360 to 180

        // Use GSAP to create a smooth, lerping rotation effect
        gsap.to(svgRotation, { rotation: rotationDegrees, duration: 2.5, ease: "power3.out" }); // Increased duration for smoother effect
    });
</script>

 

Optimized GSAP Code

Here is the solution we propose to optimize the above code.

<section class="overflow-hidden py-4 py-lg-0 pb-lg-9 position-relative">
	<div class="position-relative mb-6 mb-lg-4 mb-xl-0">
		<img class="position-absolute rotation top-15 top-lg-35 top-xxl-0 start-0 start-xl-15 start-xxl-25 w-100 h-100 z-n1 " src="https://ui.bootstrap.ninja/wp-content/uploads/2024/01/cosmos.svg">
	</div>
</section>

<!-- the other components are intentionally omitted to keep the code readable, Inspect the code of our homepage at https://ui.bootstrap.ninja/ -->

<!-- Load GSAP Core asynchronously -->
<script async="" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>

<!-- Load ScrollTrigger plugin asynchronously and initialize animations once it's loaded -->
<script async="" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/ScrollTrigger.min.js" onload="initGsapAnimations();"></script>

<script>
    function initGsapAnimations() {
        // Ensure both GSAP and ScrollTrigger are loaded
        if (window.gsap && window.ScrollTrigger) {
            gsap.registerPlugin(ScrollTrigger);

            // Select the SVG with the rotation class
            const svgRotation = document.querySelector('.rotation');

            // Listen for scroll events on the window
            window.addEventListener('scroll', () => {
                // Calculate the rotation based on scroll position
                let scrollPercent = window.scrollY / (document.body.offsetHeight - window.innerHeight);
                let rotationDegrees = scrollPercent * 270; // Adjust rotation factor as needed

                // Use GSAP to create a smooth, lerping rotation effect
                gsap.to(svgRotation, { rotation: rotationDegrees, duration: 2.5, ease: "power3.out" });
            });
        } else {
            console.error("GSAP or ScrollTrigger not loaded");
        }
    }
</script>