Adding Custom JavaScript
π¦ Adding Custom JavaScript to a Shopify Theme
To extend your theme with custom JavaScript logic (e.g., animations, tracking events, or custom UI interactions), you should follow this structured approach.
β
Step 1: Create custom.js
custom.jsCreate a new JavaScript file in your themeβs assets directory.
Path:
/assets/custom.js
π‘ This file will contain all your custom JavaScript logic. It will be loaded on all storefront pages if added correctly in the next steps.
β
Step 2: Include custom.js in Your Layouts
custom.js in Your LayoutsYou need to include your custom.js file in two theme layout files:
theme.liquidβ used across most storefront pagespassword.liquidβ used for the storefront password/login page
Path:
/layout/theme.liquid
/layout/password.liquid
Insert the following line:
After this line (usually already present):
<script src="{{ 'global.js' | asset_url }}" defer="defer"></script>Add this:
β οΈ Make sure
custom.jsis inserted after all required scripts (likeglobal.js) to ensure dependencies are loaded first.
β
Example
π Best Practices
Use
deferto prevent blocking page rendering.Wrap your code inside
DOMContentLoadedorwindow.onloadto ensure the DOM is fully available:
Avoid using jQuery unless itβs already part of the theme. Use vanilla JS whenever possible.
Keep your logic modular and avoid polluting the global scope.
π Useful References
Shopify official: π Working with Assets
DOM Events: π MDN β DOMContentLoaded π MDN β Defer vs Async