What better way to celebrate the 50th #GTMTips article than, well, a really useful Google Tag Manager tip?! This tip is so useful and simple; it encapsulates everything that I had in mind when starting this series. The tip is about restricting scope of Custom HTML Tags. This is an important concept, because it’s possible that you’re stuffing your page’s global JavaScript namespace with all sorts of junk, and thus inadvertently causing conflicts.
The Simmer Newsletter
Follow this link to subscribe to the Simmer Newsletter! Stay up-to-date with the latest content from Simo Ahava and the Simmer online course platform.
Tip 50: Restrict Custom HTML Tag Scope
The tip is very simple. Whenever adding JavaScript code in a Custom HTML Tag between <script>
and </script>
tags, add the following code around whatever you’ve written:
(function() {
// Your JavaScript here
})();
What you’re doing is creating an immediately invoked function expression, or IIFE for short. By wrapping the function() {...}
in parentheses, you’re instructing the browser to treat the code within as an expression rather than a declaration. In other words, you’re instructing the browser to invoke the function, making it syntactically valid by adding the empty parentheses at the end (so that the browser knows it’a a function expression). This executes whatever code is within the <script/>
block.
So if it does exactly what it would do even without the IIFE, why do it?
Well, JavaScript scopes variables to their execution context. This means that if variables are declared within a function, they are only accessible inside that function. Furthermore, JavaScript has a global namespace which in the web browser is defined by the window
object. If you didn’t have the IIFE around your code, then any variables you declared would be hoisted to the global window
namespace, thus creating potential for conflict.
Take a look at this example:
<script>
// No IIFE
var ga = "My secret 'ga' code";
console.log(ga);
// Results in an error
window.ga('send', 'pageview');
</script>
By overwriting ga
with your own nifty little string, you just broke Universal Analytics. Congratulations.
Whereas if you did this:
<script>
(function() {
// IIFE
var ga = "My secret 'ga' code";
console.log(ga);
})();
// Works
window.ga('send', 'pageview');
</script>
This time you’re protecting your own little ga
variable and, more importantly, you’re protecting the global ga
function by declaring your variable in an IIFE.
Just remember the following additional tips:
-
Always declare variables in GTM using the
var
keyword. This way they will be restricted to the current scope. If you omit this keyword, then JavaScript automatically adds them to the globalwindow
namespace. NOTE! This also applies to Custom JavaScript Variables, not just Custom HTML Tags! -
Always refer to global variables using the
window.
prefix. That will make your code more readable and will prevent you from causing conflicts by accident.
And that’s it!