load hubspot code for forms deferred

/**
* Conditionally load the HubSpot forms script.
*
* This function enqueues the script on all pages except for single posts,
* single ‘giveaway’ custom posts, and a specific list of excluded pages.
*/
function zeevou_enqueue_hubspot_forms_script() {

// — START CUSTOMIZATION —
// Add page IDs or slugs to this array to exclude them.
$excluded_pages = array(
‘free-demo’ // Excludes the page with the slug ‘/free-consultation’.
);
// — END CUSTOMIZATION —

// Conditions for exclusion. Do NOT load the script if any of these are true.
$is_excluded = false;

// Condition 1: Is it a single blog post OR a single ‘giveaway’ page?
if ( is_singular( array( ‘post’, ‘giveaway’ ) ) ) {
$is_excluded = true;
}

// Condition 2: Is it one of the pages listed in our $excluded_pages array?
if ( ! $is_excluded && is_page( $excluded_pages ) ) {
$is_excluded = true;
}

// If none of the exclusion conditions were met, load the script.
if ( ! $is_excluded ) {
wp_enqueue_script(
‘hubspot-forms-embed’, // A unique name for the script. This is important!
‘https://js.hsforms.net/forms/embed/5552032.js’, // The script URL.
array(), // No dependencies.
null, // No version number.
true // Load in the footer for better page performance.
);
}
}
add_action( ‘wp_enqueue_scripts’, ‘zeevou_enqueue_hubspot_forms_script’ );

/**
* NEW FUNCTION: Add ‘defer’ attribute to the HubSpot script tag.
*
* This function targets the script by its unique name (‘hubspot-forms-embed’)
* and modifies its HTML tag to include the defer attribute.
*/
function zeevou_add_defer_to_hubspot_script( $tag, $handle, $src ) {
// Check for our specific script’s handle.
if ( ‘hubspot-forms-embed’ === $handle ) {
// Add the defer attribute to the script tag.
$tag = str_replace( ‘ src’, ‘ defer src’, $tag );
}
return $tag;
}
add_filter( ‘script_loader_tag’, ‘zeevou_add_defer_to_hubspot_script’, 10, 3 );

Scroll to Top
Solution lamp for mobile header

Custom Solutions with Zeevou

Discover tailored solutions perfectly suited to your role, business size, and specific use cases.