Skip to content

Instantly share code, notes, and snippets.

@mattheu
Last active December 1, 2023 17:52
Show Gist options
  • Save mattheu/21481c374a207acfe8c7ca3846763e87 to your computer and use it in GitHub Desktop.
Save mattheu/21481c374a207acfe8c7ca3846763e87 to your computer and use it in GitHub Desktop.
Altis consent - Defer loading of scripts.
<?php
/**
* Defer loading of scripts until consent given (using Altis consent API).
*
* Note this requires the script to be enqueued in the normal manner.
* Scripts are loaded async so must be compatible with this, can't have dependencies etc.
*
* @package
*/
namespace HM\DeferScriptsUntilConsentGiven;
// Store defer loaded scripts.
$defer_scripts_until_consent_given = [];
global $defer_scripts_until_consent_given;
/**
* Setup hooks.
*/
function setup() {
add_filter( 'wp_enqueue_scripts', __NAMESPACE__ . '\\scripts_and_styles', 100 );
add_action( 'wp_footer', __NAMESPACE__ . '\\load_script_based_on_consent', 100 );
add_filter( 'script_loader_tag', __NAMESPACE__ . '\\disable_scripts_that_require_consent', 100, 3 );
}
function scripts_and_styles() {
wp_script_add_data( 'hubspot-form', 'require-consent', 'marketing' );
}
function load_script_based_on_consent() {
global $defer_scripts_until_consent_given;
if ( empty( $defer_scripts_until_consent_given ) ) {
return;
}
?>
<script>
( function() {
const scripts = <?php echo wp_json_encode( $defer_scripts_until_consent_given ); ?>
// Load the script dynamically
function loadScript( src, handle ) {
var script = document.createElement('script');
script.src = src;
script.async = true;
script.id = handle + '-js';
document.body.appendChild(script);
}
Object.keys( scripts ).forEach( consentCategory => {
if ( Altis.Consent.has( consentCategory ) ) {
scripts[ consentCategory ].forEach( script => loadScript( script.src, script.handle ) );
}
} )
document.addEventListener( 'wp_listen_for_consent_change', function( event ) {
Object.keys( scripts ).forEach( consentCategory => {
if ( event.detail[ consentCategory ] && event.detail[ consentCategory ] === 'allow' ) {
scripts[ consentCategory ].forEach( script => loadScript( script.src, script.handle ) );
}
} );
} );
} )();
</script>
<?php
}
function disable_scripts_that_require_consent( $tag, $handle, $src ) {
global $defer_scripts_until_consent_given;
$consent_category = wp_scripts()->get_data( $handle, 'require-consent' );
if ( $consent_category ) {
$defer_scripts_until_consent_given[ $consent_category ][] = [ 'handle' => $handle, 'src' => $src ];
return '';
}
return $tag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment