-
-
Save pavlo-bondarchuk/7fbc67d69308810613076a52c0b1ebd0 to your computer and use it in GitHub Desktop.
Painless 3rd party marketing scripts in WordPress
This file contains hidden or 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 | |
| // Enqueue all js codes combined in a single file. | |
| function enqueue_theme_assets() | |
| { | |
| wp_enqueue_script( | |
| 'trackers', | |
| get_stylesheet_directory_uri() . '/js/trackers.js', | |
| null, | |
| null, | |
| true | |
| ); | |
| } | |
| add_action( 'wp_enqueue_scripts', 'enqueue_theme_assets' ); | |
| // Defer this script. | |
| function add_defer_attribute( $tag, $handle ) | |
| { | |
| if ( is_admin() ) { | |
| return $tag; | |
| } | |
| // Script handles to defer | |
| $defer_handles = [ | |
| 'trackers', | |
| ]; | |
| if ( in_array( $handle, $defer_handles, true ) ) { | |
| return str_replace( ' src', ' defer="defer" src', $tag ); | |
| } | |
| return $tag; | |
| } | |
| add_filter( 'script_loader_tag', 'add_async_attribute', 10, 2 ); | |
| // Preconnect all external URLs that will be requested from that scripts. | |
| function resource_hints( $hints, $relation_type ) | |
| { | |
| if ($relation_type === 'preconnect') { | |
| $hints[] = '//www.googletagmanager.com'; | |
| $hints[] = '//www.google-analytics.com'; | |
| $hints[] = '//www.gstatic.com'; | |
| } | |
| return $hints; | |
| } | |
| add_filter( 'wp_resource_hints', 'resource_hints', 10, 2 ); |
This file contains hidden or 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
| var fired = false; | |
| window.addEventListener('scroll', () => { | |
| if (fired === false) { | |
| fired = true; | |
| setTimeout(() => { | |
| // Google Tag Manager | |
| (function (w, d, s, l, i) { | |
| w[l] = w[l] || []; | |
| w[l].push({ | |
| 'gtm.start': | |
| new Date().getTime(), event: 'gtm.js' | |
| }); | |
| var f = d.getElementsByTagName(s)[0], | |
| j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; | |
| j.async = true; | |
| j.src = | |
| 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; | |
| f.parentNode.insertBefore(j, f); | |
| })(window, document, 'script', 'dataLayer', 'YOUR_PROPERY_ID'); | |
| }, 1000) | |
| } // endif | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment