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

Create 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

You need to include your custom.js file in two theme layout files:

  • theme.liquid – used across most storefront pages

  • password.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.js is inserted after all required scripts (like global.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 defer to prevent blocking page rendering.

  • Wrap your code inside DOMContentLoaded or window.onload to 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