Archive for September, 2022


Wait for async JQuery to load

Moving JQuery to loading asynchronously can greatly improve your site’s loading time, but can cause issues with any scripts you may have on your site that are dependent on JQuery.  To wait until the document is ready to be manipulated you can usually just use

1
2
3
$(function() {
  // Handler for .ready() called.
});

But, $ may not be available if you’re loading JQuery asynchronously.  So you need to change that to wait until JQuery is available using vanilla JavaScript

1
2
3
4
5
6
7
8
9
10
var jqready = function(method) {
    if (window.$) {
        $(function() { method(); });
    } else {
        setTimeout(function() { jqready(method) }, 50);
    }
};
jqready(function() {
  //ready to use JQuery!
});

But, that’s a bit buky so here is a minified version

1
2
3
4
var jqready = (m)=>{(window.$)?($(()=>{m()}):(setTimeout(()=>{jqready(m)}, 50))};
jqready(function() {
  //ready to use JQuery!
});

Reference:
https://stackoverflow.com/questions/7486309/how-to-make-script-execution-wait-until-jquery-is-loaded
https://api.jquery.com/ready/

Permalink » No comments

Remove styles and scripts from wp_head

wp_head can add a lot into your header.  I was working on improving a site’s loading time and wanted to remove some scripts and styles that weren’t being used in the front end.

First, you can use this code to display all the styles and scripts that have been enqueued:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function crunchify_print_scripts_styles() {
 
    $result = [];
    $result['scripts'] = [];
    $result['styles'] = [];
 
    // Print all loaded Scripts
    global $wp_scripts;
    foreach( $wp_scripts->queue as $script ) :
       $result['scripts'][] =  $script.' : '.$wp_scripts->registered[$script]->src . ";";
    endforeach;
 
    // Print all loaded Styles (CSS)
    global $wp_styles;
    foreach( $wp_styles->queue as $style ) :
       $result['styles'][] =  $style.' : '.$wp_styles->registered[$style]->src . ";";
    endforeach;
 
    return $result;
}
 
print_r( crunchify_print_scripts_styles() );

Then you can remove specific ones by adding them into the “excess” array and adding this script above your call to wp_head

1
2
3
4
5
6
7
8
9
10
11
function remove_extra_styles() {
	$excess = ['script1','style1'];
 
	foreach($excess as $e) {
		wp_deregister_style($e);
		wp_dequeue_style($e);
		wp_dequeue_script($e);
		wp_deregister_script($e);		
	}
}
add_action( 'wp_enqueue_scripts', 'remove_extra_styles', 100 );

Sources:

https://wordpress.stackexchange.com/questions/233140/how-can-i-get-a-list-of-all-enqueued-scripts-and-styles
https://wordpress.stackexchange.com/questions/246547/remove-all-theme-css-js-from-wp-head-but-only-for-1-page-template

 

Permalink » No comments