Partners: Wrap Theme Scripts in an IIFE

Community Manager
Community Manager
175 4 194
Hello Developers,
We are reaching out in regard to some recent changes to our Themes coding. We recently noticed some shops’ themes include code that goes against best practices, please see instructions below to resolve this issue.
The current impacted code looks like:
var a, b, c; function d () {...}
This can be in an inline script or an external script that is referenced in a script tag, for example:
  var a, b, c; function d () {...}
It's extremely rare for this to be human generated, more often than not it is the result of bundling JavaScript code (with a bundler such as Rollup, Esbuild, and Webpack depending on the configuration), and then minifying it (with a minifier such as UglifyJS, Closure compiler, etc.). When minifying JavaScript, minifiers will rename JavaScript variables to be shorter, for example:
var myLongVariable;

function myFunctionName() {
This will be minified to:
var a; function b() {}
This is common practice and is not problematic, assuming that the JavaScript code does not pollute the global namespace. JavaScript variables and functions that are defined in the global scope can collide with one another. The scope is the current context of execution in which values and expressions are "visible" or can be referenced. So if another minified script also defines values with the same name on the global scope, there will be a collision.
To avoid namespace collision in the global scope, JavaScript values should be wrapped in a function scope. Values defined within the scope of a function are only available within the scope of that function, and do not clash with variables defined on the global scope.The IIFE pattern (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined:
(function () {
  var a; function b() {}
Following this pattern ensures that values defined by a script do not pollute the global namespace, and are scoped to the function scope that is created by the IIFE. Scripts injected in themes should always be wrapped in an IIFE to ensure there are no global namespace collisions.
We are always working to improve merchant and customer experience on our platform and we continue to make updates to improve performance. Should you have any questions in regard to these changes please feel free to contact Shopify Partner Support or start a new thread in Online Store 2.0.
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution

- To learn more visit the Shopify Help Center or the Shopify Blog

Replies 0 (0)