Skip to content

Instantly share code, notes, and snippets.

@vaughnroyko
Created September 24, 2019 16:44
Show Gist options
  • Save vaughnroyko/aff0765b8d618be2ff1f79b56ed15ea8 to your computer and use it in GitHub Desktop.
Save vaughnroyko/aff0765b8d618be2ff1f79b56ed15ea8 to your computer and use it in GitHub Desktop.
Defer Scripts in Wordpress
<?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