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:
<script src="{{ 'custom.js' | asset_url }}" defer="defer"></script>⚠️ Make sure
custom.jsis inserted after all required scripts (likeglobal.js) to ensure dependencies are loaded first.
✅ Example
<!-- Existing scripts -->
<script src="{{ 'global.js' | asset_url }}" defer="defer"></script>
<!-- Custom script -->
<script src="{{ 'custom.js' | asset_url }}" defer="defer"></script>🛠 Best Practices
Use
deferto prevent blocking page rendering.Wrap your code inside
DOMContentLoadedorwindow.onloadto ensure the DOM is fully available:
document.addEventListener('DOMContentLoaded', function () {
// Your code here
});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