Mimicking WP Rocket’s “Delay JavaScript” Functionality on Non-WP Sites

One of WP Rocket’s most powerful features is its ability to delay non-mission-critical JavaScript from loading until a user interaction is detected.

This way, visitors load everything above-the-fold first, like images, CSS styles, and things that will give the appearance of a faster loading website. These things are more important than scripts that are further down on the page, or that aren’t even needed on this page at all.

For non-WordPress sites, you can use this script I created to delay JavaScript similarly:

<!-- Comment out existing JS that we want to lazy load -->
<div id="deferred-scripts"> <!--


   <!-- Plop your JS below here -->
   <script src="/slow-script.js"></script>
   <script>// Example inline code</script>
   <script src="/something-not-very-important.js"></script>


--></div>
<!-- End JS that we want to lazy load -->

<script>
// Function to execute deferred scripts
function executeScripts() {
    var container = document.getElementById('deferred-scripts');
    var scripts = container.innerHTML.match(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi);
    if (scripts) {
        scripts.forEach(function(scriptTag) {
        var newScript = document.createElement('script');
        var srcMatch = scriptTag.match(/src=['"]([^'"]+)['"]/);
    if (srcMatch) {
        newScript.src = srcMatch[1];
    } else {
        var inlineScript = scriptTag.replace(/<script\b[^<]*>|<\/script>/gi, "").trim();
        newScript.innerHTML = inlineScript;
    }
    document.body.appendChild(newScript);
});
}
container.parentNode.removeChild(container);
window.removeEventListener('scroll', executeScripts);
window.removeEventListener('mousemove', executeScripts);
}
window.addEventListener('scroll', executeScripts, { once: true });
window.addEventListener('mousemove', executeScripts, { once: true });
</script>

Give it a try and let me know what you think. This should help your PageSpeed Insights scores and overall load times.

Here’s a backup in Pastebin in-case WordPress messes up the code, as it’s known to do:
https://pastebin.com/raw/DmDGeRyB

What People Are Saying:

No comments yet. Be the first!

Leave a Reply

Copyright 2024, All rights reserved. Yadda yadda.