Customizing Google Optimize page hiding snippet
Google’s “Optimize Page-Hiding Snippet" is a feature of the Google Optimize A/B testing product. The snippet hides your entire page until Optimize is able to execute any A/B tests you have running. It works by (1) adding a class to the <body>
element that hides everything, then (2) removes that class once the Optimize dataLayer’s "hide.end" function is called. It also includes a timeout in case there’s a script error and the experiment(s) fail to download. For more detail, Google has provided the annotated source code in their documentation.
A better user experience would be to paint elements ASAP that won’t be subject to any A/B test. The sooner you can get something on the screen, the lower the risk of a bounce due to perceived slowness.
To selectively hide page elements, determine which elements will likely be the subject of an A/B test now or in the future. The elements you pick don't have to be small, they can even be top-level containers in your HTML. You'll need to add a class, "async-hide", to each of these elements on the server.
Next, modify the JavaScript portion of the page-hiding snippet to look something like this:
JavaScript
(function (a, s, y, n, c, h, i, d, e) {
h.start = 1 * new Date();
h.end = i = function () {
document.querySelectorAll("." + y).forEach(function (e) {
e.className = e.className.replace(RegExp(" ?" + y), "");
});
};
(a[n] = a[n] || []).hide = h;
setTimeout(function () {
i();
h.end = null;
}, c);
h.timeout = c;
})(window, null, "async-hide", "dataLayer", 4000, { "GTM-XXXXXX": true });
Compared to the official snippet, I've removed the parts that manipulate classes on the <html>
element, and replaced them with a loop over every element that loads with ".async-hide" already present.
More explicitly, I replaced this line:
s.className = s.className.replace(RegExp(" ?" + y), "");
with this:
document.querySelectorAll("." + y).forEach(function (e) {
e.className = e.className.replace(RegExp(" ?" + y), "");
});
and removed the initial addition of ".async-hide" to the <html>
element. Elements without the .page-hide class will load normally, giving your users something to engage with while the Optimize tests continue to load.
Legal Note
I'm providing this snippet as an example of how to customize a Google product. I don't believe its usage violates Optimize's terms of service in any way, but just in case: "use at your own risk". This post & associated website are neither official documentation, nor are they endorsed by anyone or any entity except myself.