Created
June 18, 2020 17:52
-
-
Save tradesouthwest/4364d64561ff35ef0584d1dcdd9293a9 to your computer and use it in GitHub Desktop.
Defer loading of external javascripts, like google ads [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 | |
/** | |
* Defer loading javascript for unregistered scripts (ads) | |
* @uses $tag(string) The <script> tag for the enqueued script. | |
* @uses $handle(string) The script's registered handle. | |
* @uses $src(string) The script's source URL. | |
* @see https://developer.wordpress.org/reference/hooks/script_loader_tag/ | |
*/ | |
/*function to add async and defer attributes*/ | |
function colormag_child_add_defer_jstags( $tag, $handle ){ | |
wp_register_script('osd_listener', | |
'https://www.googletagservices.com/activeview/js/current/osd_listener.js', | |
[], null, true); | |
wp_register_script('abg_lite', | |
'https://tpc.googlesyndication.com/pagead/js/r20200610/r20110914/abg_lite.js', | |
[], null, true); | |
wp_register_script('qs_click_protection', | |
'https://tpc.googlesyndication.com/pagead/js/r20200610/r20110914/client/qs_click_protection.js', | |
[], null, true); | |
wp_enqueue_script('osd_listener'); | |
wp_enqueue_script('abg_lite'); | |
wp_enqueue_script('qs_click_protection'); | |
## 1: list of scripts to defer. (Edit with your script names) | |
$defer_scripts = array( | |
'osd_listener', | |
'abg_lite', | |
'qs_click_protection' | |
); | |
foreach($defer_scripts as $defer_script) { | |
if ($defer_script === $handle) { | |
return str_replace(' src', ' defer="defer" src', $tag); | |
} | |
} | |
return $tag; | |
} | |
add_filter( 'script_loader_tag', 'colormag_child_add_defer_jstags', 10, 2 ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment