Skip to content

Instantly share code, notes, and snippets.

@mikeselander
Created July 15, 2015 00:56
Show Gist options
  • Save mikeselander/f70c4e50243857bc6525 to your computer and use it in GitHub Desktop.
Save mikeselander/f70c4e50243857bc6525 to your computer and use it in GitHub Desktop.
Asyn & Defer scripts
/**
* Add possibility to asynchroniously load javascript files
*
* Filters all URL strings called in clean_url() for the #asyncload value
* and replaces said string with async='async'
*
* @param string $url The URL for the script resource.
* @returns string Modified script string
*/
add_filter('clean_url', 'add_async_forscript', 11, 1);
function add_async_forscript( $url ){
if ( strpos( $url, '#asyncload' ) === false ){
return $url;
} elseif ( is_admin() ){
return str_replace( '#asyncload', '', $url );
} else {
return trim( str_replace( '#asyncload', '', $url ) ) . "' async='async";
}
}
/**
* Add possibility to Defer load javascript files
*
* Filters all URL strings called in clean_url() for the #deferload value
* and replaces said string with defer='defer'
*
* @param string $url The URL for the script resource.
* @returns string Modified script string
*/
add_filter('clean_url', 'add_defer_forscript', 11, 1);
function add_defer_forscript( $url ){
if ( strpos( $url, '#deferload' ) === false ){
return $url;
} elseif ( is_admin() ){
return str_replace( '#deferload', '', $url );
} else {
return trim( str_replace( '#deferload', '', $url ) ) . "' defer='defer";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment