Created
February 12, 2022 02:52
-
-
Save igor-ribeiro/8479b02c0fa960b8fb5d8a448ad5d0f4 to your computer and use it in GitHub Desktop.
GTM Helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var GTM_LOADER = { | |
| MAX_TRIES: 5, | |
| TRY_TIMEOUT: 5000, | |
| tries: {}, | |
| waiting: {}, | |
| onReady: function onReady(cb, deps) { | |
| var key = deps.join(); | |
| if (key in this.tries === false) { | |
| this.tries[key] = 0; | |
| } | |
| if (this.tries[key] >= this.MAX_TRIES) { | |
| console.info( | |
| 'Timeout of', | |
| this.TRY_TIMEOUT * this.MAX_TRIES, | |
| 'ms execeeded waiting for modules', | |
| deps | |
| ); | |
| return; | |
| } | |
| if (key in this.waiting === false) { | |
| this.waiting[key] = []; | |
| } | |
| this.waiting[key] = deps.map(function (dep) { | |
| return window[dep] != null; | |
| }); | |
| var loaded = this.waiting[key].filter(Boolean); | |
| if (loaded.length !== this.waiting[key].length) { | |
| console.log( | |
| 'Dependencies', | |
| this.waiting[key].map(function (loaded, i) { | |
| return loaded ? false : deps[i]; | |
| }).filter(Boolean), | |
| 'are not loaded yet. Trying again in', | |
| this.TRY_TIMEOUT, | |
| 'ms' | |
| ); | |
| setTimeout(function () { | |
| this.tries[key]++; | |
| this.onReady(cb, deps); | |
| }.bind(this), this.TRY_TIMEOUT) | |
| return; | |
| } | |
| delete this.waiting[key]; | |
| delete this.tries[key]; | |
| cb(); | |
| } | |
| } | |
| function GTM_dispatchCustomEvent(name, detail) { | |
| window.dispatchEvent( | |
| new CustomEvent(name, { detail: detail }) | |
| ); | |
| } | |
| function GTM_cacheGuard(event, data, cb) { | |
| if (window.localStorage.getItem(event) === '1') { | |
| console.info(event, '- Event already sent'); | |
| return; | |
| } | |
| try { | |
| cb(); | |
| console.info(event, data); | |
| window.localStorage.setItem(event, 1); | |
| } catch(e) { | |
| console.error(event, '- Error sending event:', e); | |
| window.localStorage.removeItem(event); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment