DEV Community

Discussion on: Can you explain to me what's going on in this code?

Collapse
 
nektro profile image
Meghan (she/her) • Edited

TLDR: What this snippet does is assign a class, namely 'async-hide' to the <html> element of our document, waits 4 seconds, and then removes it.

We have a self running function with a bunch of parameters but let's "prettify" it first.

(function (a, s, y, n, c, h, i, d, e) {
    s.className += ' ' + y;
    h.start = 1 * new Date();
    h.end = i = function () {
        s.className = s.className.replace(RegExp(' ?' + y), '')
    };
    (a[n] = a[n] || []).hide = h;
    setTimeout(function () {
        i();
        h.end = null
    }, c);
    h.timeout = c;
})(window, document.documentElement, 'async-hide', 'dataLayer', 4000, { 'GTM-PNDQRRW': true });

Hmmm. That didn't help much. Okay. Let's replace all the parameters with their actual variables.

(function (h, i, d, e) {
    document.documentElement.className += ' ' + 'async-hide';
    h.start = 1 * new Date();
    h.end = i = function () {
        document.documentElement.className = document.documentElement.className.replace(RegExp(' ?' + 'async-hide'), '')
    };
    (window['dataLayer'] = window['dataLayer'] || []).hide = h;
    setTimeout(function () {
        i();
        h.end = null
    }, 4000);
    h.timeout = 4000;
})({ 'GTM-PNDQRRW': true });

Much better. Now we have left the options object being passed as h, i only being used as variable declaration, and d and e are unused other than making the original parameter list async hide.

  • document.documentElement represents the <html> element
  • .className += ' ' normalizes our variable to a String and is setting the class attribute on `
  • + 'async-hide'; sets the class to async-hide which will be used later.
  • h.start = 1 * new Date(); sets on our options Object a time 1 second from now
  • h.end = i = function () sets the end property and assigns our i parameter a value
  • document.documentElement.className = document.documentElement.className.replace(RegExp(' ?' + 'async-hide'), '') really convoluted way to remove only the async-hide class from <html>
  • (window['dataLayer'] = window['dataLayer'] || []) grabs the dataLayer list from Google Tag Manager or returns an empty Array
  • .hide = h; sets the hide property to out options object
  • i(); calls our function to remove the class
  • h.end = null removes the reference to our function from the options object
  • h.timeout = 4000; the snippet waits 4 seconds before doing anything

So.

What this snippet does is assign a class, namely 'async-hide' to the <html> element of our document, waits 4 seconds, and then removes it.

Addendum, and I almost forgot! The CSS makes the entire document invisible. Presumably to wait for the page to load and hoping everything is done by then so as to not get a FOUC or similar.

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

1*new Date() turns the date object into an integer.