concept global variable in category javascript

appears as: global variables, global variable
Third-Party JavaScript

This is an excerpt from Manning's book Third-Party JavaScript.

2.5.4. Using global variables

In the past few sections, we’ve explored using the DOM as a means of passing parameters to your third-party application. An alternate approach is to avoid the DOM entirely, and instead use global variables. Any variables declared in the browser’s topmost variable scope are attached to the window object, and are accessible by any script running on the page.

The next listing changes the script include snippet from section 2.1 to declare a global variable whose purpose is to pass the product ID to your third-party script.

Listing 2.10. Passing script arguments using global variables
<script> var product_id = 1234; (function() { var script = document.createElement('script'); script.async = true; script.src = 'http://camerastork.com/widget.js'; var entry = document.getElementsByTagName('script')[0]; entry.parentNode.insertBefore(script, entry); })(); </script>

Is there a benefit to using global variables to pass parameters over embedding them in the DOM, either via the query string or fragment identifier, or using data-* attributes? Sure. For starters, you can embed any type of JavaScript object as a parameter, like a dictionary object. And embedding parameters as global variables is, debatably, more clear to publishers than appending them to the end of a long URL. Last, unlike the other techniques we covered, you don’t need to query the DOM in order to extract the parameters—they’re already initialized as JavaScript variables for you. When performance matters above all else, global variables may be the best choice. Table 2.1 summarizes the pros and cons of the various techniques.

Table 2.1. Pros and cons of parameter-passing techniques

Technique

Pros

Cons

Query string Uses URL, passed to server Must query DOM, less cache-able
Fragment identifier Uses URL, easy to cache Must query DOM
Data-* attributes Easy to read, easy to cache, can locate script include snippet Must query DOM
Global variables Easy to read, easy to cache, flexible argument types, don’t need to query DOM Global variables

Each of the four methods we covered in this section—using the query string, the fragment identifier, data-* attributes, and global variables—have their own pros and cons (see table 2.1). Which you use will depend largely on your type of application. Some widgets will probably make use of data-* attributes because they enable the application to locate the position of the script include snippet in the DOM. Analytics scripts might use global variables for their configurability and performance. Using the query string might seem like the odd man out, but there may be cases where passing parameters to the server when requesting the script file is preferred. Just remember that whatever you implement, it’ll be difficult to switch later—so choose wisely.