For discussing the development and usage of Checkout UI extensions, post-purchase extensions, web pixels, Customer Accounts UI extensions, and POS UI extensions
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
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.