Created
September 24, 2019 16:44
-
-
Save vaughnroyko/aff0765b8d618be2ff1f79b56ed15ea8 to your computer and use it in GitHub Desktop.
Defer Scripts in Wordpress
This file contains 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
<?php | |
// Async/defer loading, fallback jQuery support | |
function modify_scripts($tag, $handle, $src) { | |
// The handles of the enqueued scripts we want to defer | |
$defer_scripts = array( | |
'lightlightbox', | |
'main' | |
); | |
if (in_array($handle, $defer_scripts)) { | |
return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n"; | |
} | |
// Fallback for jQuery | |
if ($handle === 'jquery') { | |
return '<script src="' . $src . '" type="text/javascript"></script>' . "\n" . '<script>if (!window.jQuery) { document.write(\'<script src="' . get_bloginfo('template_directory') . '/js/lib/jquery-3.4.1.min.js"><\/script>\'); }</script>' . "\n"; | |
} | |
return $tag; | |
} | |
add_filter('script_loader_tag', 'modify_scripts', 10, 3); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment