How to Optimize a Theoretical Funnel Page Load Speed

Ciprian on Tuesday, May 17, 2022 in Methods, Events and Scopes

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Here’s a quick snippet to preload the next step in a theoretical funnel/workflow:

PHP

<?php
/**
 * Preconnect/Prefetch/Prerender in HTML5
 */
if (stripos(getPageUrl(), 'funnel/step-one') !== false) {
    // Firefox
    echo '<link rel="prefetch" href="' . str_replace('funnel/step-one', 'funnel/step-two', getPageUrl()) . '">';
    // Chrome
    echo '<link rel="prerender" href="' . str_replace('funnel/step-one', 'funnel/step-two', getPageUrl()) . '">';
}
?>

JavaScript

<script>
/**
 * Preconnect/Prefetch/Prerender in JS
 */
function preconnectTo(url) {
    let hint = document.createElement('link');
    hint.rel = 'preconnect';
    hint.href = url;
    document.head.appendChild(hint);
}

// Usage
if (window.location.href.indexOf('funnel/step-one') > -1) {
    preconnectTo(window.location.href.replace('funnel/step-one', 'funnel/step-two'));
}

// Usage (alternative)
if (/step-one/.test(self.location.href)) {
    preconnectTo(self.location.href.replace('funnel/step-one', 'funnel/step-two'));
}
</script>

Related posts

Leave a Reply