Setup Google Optimize anti-flickering script on NextJS/ReactJS

Viewed 3085

On a NextJS/ReactJS project, I attempt setting up Google Optimize for some experiments. What I want to avoid though is the flickering effect it has while Optimize is changing the visual elements on each experiment.

For this cause, I have used the anti-flicker script suggested by Google. Now, while this works on initial load, practically "hiding" the entire page for some time in order for Optimize to apply changes, this does not work on my case in terms of client-side routing, as the full reload of a page does not occur in that case.

Therefore, I "avoid" flickering on initial page load, but I have not managed to make it work in terms of client-side routing, as the initial script does not execute again - and even if it did, the result would not be ideal.

Please note that hiding and re-displaying the page is not an option (like re-initiating the script via a history change event), as this breaks the continuity client-side routing provides. Also, hiding temporarily the component that is flickered is not proven easy, as I am not sure at which step of the routing process should I hide it and I did not manage to make it be displayed in an effective way. Thoughts?

Thank you very much in advance.

1 Answers

This solution may or may not work with your use-case but I use this solution for most of the Google Optimize experiments and have been able to create complex AB tests with it.

  1. Define Activation event in you experiment's settings.
  2. Initialize the experiment using useEffect
  3. Use React or Redux state to toggle components using eventCallback property.

Sample component:

const ExperimentalComponent = () => {
    // 0 - Original
    const [experimentType, setExperimentType] = useState("0");
    useEffect(() => {
        if(window && window.dataLayer && !isLoadingExperiment) {
            window.dataLayer.push({
                event: "my_experiment_name",
                eventCallback: () => {
                    const experimentType = window.google_optimize && window.google_optimize.get("experimentId");
                    // undefined - when experiment isn't running
                    // 1,2,3 - when ant variant is running
                    if(experimentType) {
                        setExperimentType(experimentType);
                    }

                }
            });
        }
    }, []);

    return (
        <React.Fragment>
            {/* Yes! google_optimize.get return string instead of number */}
            { experimentType === "0" && <div>Original</div> }
            { experimentType === "1" && <div>Variant 1</div> }
            { experimentType === "2" && <div>Variant 2</div> }
        </React.Fragment>
    );
};

Experiment ID

Experiment ID

Experiment trigger

Experiment trigger

References:

Related