Preloading is most useful for fetching resources that are discovered late within the page, any assets like fonts or images, that are requested via JavaScript.
It can be used to prioritize your main assets on the page, like main JavaScript.
<head> <link rel="preload" href="https://javascript_file.js" as="script" /> </head>
When we load any script like this, browser is told to download the referenced asset at high priority, skipping out priority on other resources.
How do we automate JavaScript preloading in WordPress?
Simplest way to preload the scripts in WordPress is to loop over and preload them in header. This can be achieved by simply adding few lines of code in functions.php file.
add_action('wp_head', function () { global $wp_scripts; foreach ($wp_scripts->queue as $handle) { $script = $wp_scripts->registered[$handle]; $source = $script->src . ($script->ver ? "?ver={$script->ver}" : ""); echo "<link rel='preload' href='{$source}' as='script'/>\n"; } }, 1);
We are simply looping over all the JavaScript in the header and appending JavaScript priority over other assets.
Verifying if it’s working?
Visit the website and perform inspect element.