A
A
Anita Kovaleva2019-08-08 11:48:12
Layout
Anita Kovaleva, 2019-08-08 11:48:12

How to make a competent preload Css \ JS for a site under wp?

Hello everyone, I read it - Preloading content using rel="... and the question arose of how to properly preload css and js for better optimization - I tried to use this snippet - for some reason it breaks the table in mozilla and chome styles, in ie it works and the page visually loads better, in PSI it adds from 10-20 points Are there any hacks besides this php script?

function add_rel_preload($html, $handle, $href, $media) {
if (is_admin())
    return $html;
  
$html = <<<EOT
<link rel='preload' as='style' onload="this.onload=null;this.rel='stylesheet'" 
id='$handle' href='$href' type='text/css' media='all' />
EOT;
  return $html;
}

add_filter( 'style_loader_tag', 'add_rel_preload', 10, 4 );

For js-
add_action('wp_head', function () {
        global $wp_scripts;
        foreach($wp_scripts->queue as $handle) {
            $script = $wp_scripts->registered[$handle];
            //-- Weird way to check if script is being enqueued in the footer.
            if($script->extra['group'] === 1) {
                //-- If version is set, append to end of source.
                $source = $script->src . ($script->ver ? "?ver={$script->ver}" : "");
                //-- Spit out the tag.
                echo "<link rel='preload' href='{$source}' as='script' onload='var script = document.createElement('script'); script.src = this.href; document.body.appendChild(script);'/>\n";
            }
        }
    }, 1);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Budakov, 2019-08-09
@Anitamsk

Try the absolutely free LiteSpeed ​​Cache plugin - it really helps with WP optimization:
With styles and scripts : minification, merging, Critical CSS generation ( free , unlike the rest) asynchronous loading
With images : optimization, lazy loading
With fonts : asynchronous loading
And if if the site is transferred to a hosting with a LiteSpeed ​​web server, then it will be engaged in caching, caching does not seem to work on Apache.
With it, pages load for me in 0.4-0.6 seconds and 1.2-1.6 on mobile devices according to PageSpeed ​​Insight.
The best and most convenient solution for WP, installed, configured once and forgotten. Works like clockwork, sites fly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question