Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Fix Duplicate CSS or JS tags in Theme App Extension

Fix Duplicate CSS or JS tags in Theme App Extension

LuckyLuc
Shopify Partner
10 0 1

Hi, I'm developing a theme app extension with one block.

Now if I add the block multiple times on the page the script and css tags are duplicated by the number of blocks.

 

Is there a way to include the CSS or JS only once event if there is 100 blocks scattered on the page ?

 

Thanks

Reply 1 (1)

Huptech-Web
Shopify Partner
1169 234 264

Hello @LuckyLuc 

you can solve this issue by just adding the code below.


1. Add the below js code in your block theme extension (liquid file)

 

 

  <script>
    if(!window.theme){
    window.theme = {}
     }
     window.theme.jsFile = "{{ 'theme.js' | asset_url }}";
    window.theme.cssFile = "{{ 'theme.css' | asset_url }}";
  </script>
  <script src="{{ 'renderThemeApp.js' | asset_url }}" defer></script>

 

 

2. create renderThemeApp.js and add the below code

 

 

// add JavaScript in theme extensions
var checkScriptAvailable = document.querySelector("script.theme-js")
if (!checkScriptAvailable) {
    const script = document.createElement('script');
    script.src=window.theme.jsFile;
    script.className = "theme-js"
    script.defer = true
    document.body.appendChild(script);
}
// add CSS in theme extensions
var checkCssAvailable = document.querySelector(".theme-css")
if (!checkCssAvailable)
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.className   = "theme-css";
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = window.theme.cssFile;
    link.media = 'all';
    head.appendChild(link);
}

 

 

If the solution presented meets your needs and addresses your query effectively, I encourage you to accept it as the chosen answer. This will acknowledge the support you received and aid fellow community members in identifying reliable and effective solutions for their similar concerns.
Thank you.

 

If you found this response helpful, please do like and accept the solution. Thanks!
Need support with Customizing your Shopify store?
Feel free to contact me at info@huptechweb.com or Visit our website Huptech Web.
Instant Shortcode Builder: Integrate customizable UI features anywhere in your store - No coding knowledge required