> For the complete documentation index, see [llms.txt](https://crocode.gitbook.io/elemento-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://crocode.gitbook.io/elemento-docs/developer-documentation/adding-custom-javascript.md).

# 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):

```liquid
<script src="{{ 'global.js' | asset_url }}" defer="defer"></script>
```

Add this:

```liquid
<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

```liquid
<!-- 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:

```js
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](https://shopify.dev/docs/api/liquid/filters/asset_url)
* DOM Events:\
  📘 [MDN – DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event)\
  📘 [MDN – Defer vs Async](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer)

***
