How to inject code to theme.js

Tourist
9 0 2
Hi everyone,
I'm building an app for price filter on collection page. I've integrated the design to the collection page successfully. Now I want to know how to inject the code to theme.js file to run the search functionality.
0 Likes
Highlighted
Shopify Partner
1843 170 534

If you are building an app you should not assume that theme.js even exists. Themes are not required to have a file named like that in their Assets folder. In fact, themes aren't even required to have jQuery. Even if you did check that theme.js exists, I would not recommend "injecting" anything in there - when a  theme is updated, your app's changes would all be lost and the result would be a broken theme / storefront.

 

Think of your app as an entirely self-contained unit. Do not make any assumptions about a theme beyond those required by Shopify (i.e. certain folder structures etc.) and really, for the benefit of everyone, try not to modify existing templates or assets if avoidable.

 

Best wishes!

I turn coffee in to code - since 1998
1 Like
Tourist
9 0 2
Thanks for the reply KarlOffenBerger. Then how can I implement the search functionality to the store?. One of my friend said that all the js code including search functionality is added in the theme.js file.
Thats why I asked for injecting code to the theme.js file.
0 Likes
Shopify Partner
1843 170 534

A theme has its own script features which can be in any JS file in the Assets folder and named whatever the theme designer prefers. The most common name seems to be theme.js simply because that's what is most often used by Shopify's free themes. The important part to consider is that these are theme features NOT app features or extensions. Of course, many people may customise their theme's scripts by editing and adding to the theme's default scripting files, but that would make future updates quite difficult. An app should not engage in the same practice, especially because an app's feature is not a theme feature.

 

Instead, you should be serving your own JS file. If your app relies on jQuery, you can check whether another jQuery already exists as this is very likely and you wouldn't need to load yet another one. If it doesn't you can dynamically load jQuery.

I turn coffee in to code - since 1998
1 Like
Shopify Partner
1 0 0

Hi Ajithvivid,

 

Are you asking to link your theme.js files with your theme.liqiud or template? If yes then you only need to write a line between body tags in theme.liqiud file.

 

{{ 'Theme.js' | asset_url | script_tag }} Boom.

Muhammad Daud
0 Likes