Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Last active October 7, 2021 20:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanknudtskov/32d71cbb11173669c1675874bd159bc0 to your computer and use it in GitHub Desktop.
Save yanknudtskov/32d71cbb11173669c1675874bd159bc0 to your computer and use it in GitHub Desktop.
How to defer parsing of scripts loaded with WordPress wp_enqueue_script
<?php
function yanco_defer_script_loader_tag( $tag, $handle, $src ) {
$defer = array(
'magnific-popup',
'cycle',
'script'
);
if ( in_array( $handle, $defer ) ) {
return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
}
return $tag;
}
add_filter( 'script_loader_tag', 'yanco_defer_script_loader_tag', 10, 3 );
// If you're unsure about handles, you can use this function
add_action( 'wp_print_scripts', 'yanco_output_enqueued_scripts' );
function yanco_output_enqueued_scripts() {
global $wp_scripts;
echo "Handles: ";
foreach( $wp_scripts->queue as $handle ) {
echo $handle . ', ';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment