Created
February 26, 2020 11:55
-
-
Save BoyetDgte/6318b93f95aba42f33f9c76891f01045 to your computer and use it in GitHub Desktop.
Adding DEFER or ASYNC in JS scripts via functions.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Single script | |
function make_script_defer( $tag, $handle, $src ){ | |
if ( 'wp_register_script-name-1' != $handle ) { | |
return $tag; | |
} | |
return str_replace( '<script', '<script defer', $tag ); | |
} | |
add_filter( 'script_loader_tag', 'make_script_defer', 10, 3 ); | |
// Multiple scripts (Array) | |
function add_defer_attribute($tag, $handle) { | |
// add script handles to the array below | |
$scripts_to_defer = array('wp_register_script-name-1', ‘wp_register_script-name-2’); | |
foreach($scripts_to_defer as $defer_script) { | |
if ($defer_script === $handle) { | |
return str_replace(' src', ' defer="defer" src', $tag); | |
} | |
} | |
return $tag; | |
} | |
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2); | |
// Pre-rquisite: wp_register_script and wp_enqueue_scripts. Scripts must be registered prior | |
function registering_scripts() { | |
wp_register_script( 'wp_register_script-name-1', content_url().'/path-to-file/js/owl.carousel.min.js', array(), '1.0.0', true ); | |
wp_register_script( 'wp_register_script-name-2', content_url().'path_to_js_file, array(), '1.0.0', true ); | |
} | |
add_action( 'wp_enqueue_scripts', 'registering_scripts' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment