Overview
This article contains the Gtmhub best practices for writing insight JavaScript.
The Script Tag
Only use one JavaScript tag per insight
Encapsulate all code in the script tag to prevent it from being treated as global
This prevents naming conflicts with other JS objects, particularly single variable names that are likely to be generated by a minifier
In most cases, this should be done with an IIFE
You can also use a setTimeout
❌Avoid This
|
✔️Do This
|
Use of the Console and Debugger key word
The debugger key word should not be used in “production” code. It should only be used when actively debugging something
Do not output to the console unless outputting information necessary to help debug when an unexpected error occurs
Using the console during development is OK, but clean up when done
Use of Angular
Use Angular to handle interactions between the HTML and JavaScript
Avoid using jQuery (see below) or pure JavaScript
Each insight will have its own Angular scope. Declare a variable for a reference to that scope and get it at the beginning of your code
❌Avoid This
|
✔️Do This
|
Use of jQuery
Avoid using jQuery for manipulation of the UI. Use Angular instead.
❌Avoid This
|
✔️Do This HTML
JavaScript
|
❌Avoid This
|
✔️Do This HTML
JavaScript
|
Avoid using jQuery for event handling. Use Angular instead.
❌Avoid This
|
✔️Do This HTML
JavaScript
|
JavaScript Event Handlers
Avoid using JavaScript event handlers in the HTML. Use their Angular equivalents instead.
❌Avoid This HTML
JavaScript
|
✔️Do This HTML
JavaScript
|
Making API Calls
Favor using Angular's http module for API calls when able
Use of jQuery for Ajax calls is OK, but if you modify the Angular data model after the API call finishes, you may need to use $apply() to render the changes
All API calls should handle the failure case
Or have a comment indicating why a silent failure is OK
Do not make synchronous API calls (I.E. using async: false property)
Doing so can cause the page to become unresponsive if the API takes a while
When making API calls that may take a substantial amount of time, use a processing spinner in the UI to indicate that something is happening
Avoid letting the user make multiple duplicate API calls (I.E. allowing two unintentional button clicks)
Use of 3rd Party Libraries
In general, avoid using an external library if there are any alternatives
Any library used in Gtmhub may be referenced and used in insights
Reference libraries using Angular’s require instead of script tags when available
Before using any 3rd party library, you must verify that its license allows for use in the context that you want to use it
If you are referencing a web version using a <script src=””> type tag, ensure that the location can be referenced by regular end users
See Also
Code Best Practices: Insight SQL