Using the hydrationDone Event in Stack Funnels
Overview
We've introduced a new custom event called hydrationDone in Stack's funnel and website previews. This event is triggered once the preview has fully completed its hydration process, allowing you to run your custom code seamlessly afterward.
Why Use the hydrationDone Event?
In the past, you might have experienced issues where your custom scripts executed before the preview's hydration was complete. This timing issue could disrupt the flow and functionality of your custom code. By using the hydrationDone event, you can ensure your scripts run at the right time, preventing any execution errors.
How It Works
The hydrationDone event is dispatched after the preview's hydration completes. This means you can safely add an event listener for hydrationDone and execute your code without worrying about timing issues. This is particularly useful for manipulating the DOM content after it has fully loaded.
Implementing the hydrationDone Event
To use this feature, follow these steps:
-
Add a Code Element: Insert a code element in the Stack builder where you want to include your custom script.
-
Listen for the Event: Use the following JavaScript to listen for the
hydrationDoneevent:document.addEventListener(
"hydrationDone",
() => {
// Add your custom JavaScript here
}
); -
Execute Your Code: Once the preview's DOM content is loaded and the
hydrationDoneevent is received, your custom code will execute smoothly without any race conditions.
Important Note
If your custom code is critical on page load, you may need to disable Optimize JavaScript. This feature can delay the hydration event if there is no user interaction, potentially affecting the timing of your script execution.
By following these steps, you can ensure your custom JavaScript or HTML runs efficiently within Stack's funnel and website previews.