Skip to content

Instantly share code, notes, and snippets.

@ahmedch1
Created September 3, 2022 10:59
Show Gist options
  • Save ahmedch1/d1f163066d611b62bc9003256c02568a to your computer and use it in GitHub Desktop.
Save ahmedch1/d1f163066d611b62bc9003256c02568a to your computer and use it in GitHub Desktop.
## VARVY_SCRIPT
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
/**
Defer parsing of JavaScript with code snippet from Varvy
*/
add_action( 'wp_footer', 'my_footer_scripts' );
function my_footer_scripts(){
?>
REPLACE_WITH_VARVY_SCRIPT
<?php
}
## Defer all Scripts except jquery
function defer_parsing_of_js( $url ) {
if ( is_user_logged_in() ) return $url; //don't break WP Admin
if ( FALSE === strpos( $url, '.js' ) ) return $url;
if ( strpos( $url, 'jquery.js' ) ) return $url;
return str_replace( ' src', ' defer src', $url );
}
add_filter( 'script_loader_tag', 'defer_parsing_of_js', 10 );
Source : https://kinsta.com/blog/defer-parsing-of-javascript/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment