How to add defer to Enqueued JavaScript Files in WordPress?
author
,
Fond of IT

Please tell us a way to add defer to JavaScript files which have been enqueued by plugins or custom code?

  • Total 1 Answer
  • 113
Can You answer this question?
author
,
Fond of IT

To apply defer on javascripts included by wordpress plugins, custom included javascripts using enqueue hook of wordpress. Suppose you have included below files as an example and how to apply defer on these files:


function custom_load_these_here_scripts() {
    wp_enqueue_script('cycle', get_template_directory_uri() . '/js/cycle.js');
    wp_enqueue_script('magnific-popup', get_template_directory_uri() . '/js/magnific-popup.js');  
    wp_enqueue_script('script', get_template_directory_uri() . '/js/main.js');  
  }

add_action('wp_enqueue_scripts', 'custom_load_these_here_scripts');

Apply defer to using below code:


function custom_defer_scripts( $tag, $handle, $src ) {
  $defer = array( 
    'magnific-popup',
    'cycle',
    'script'
  );
  if ( in_array( $handle, $defer ) ) {
     return '

<script src="&#39; . $src . &#39;" defer="defer" type="text/javascript"></script>
' . "\n";
  }
    
    return $tag;

add_filter( 'script_loader_tag', 'custom_defer_scripts', 10, 3 );

And how to find other handles of other unknown files:

function custom_detect_enqueued_scripts() {

global $wp_scripts;

echo "Handles: ";

foreach( $wp_scripts->queue as $handle ) :

echo $handle . ', ';

endforeach;

}

add_action( 'wp_print_scripts', 'custom_detect_enqueued_scripts' );