Shopware 6: How to add dynamic content to a page
Bruno Correia
In Shopware 6, JavaScript functionalities are split in modular “plugins” – which are added to your usual Shopware plugin. This JavaScript functionalities are automatically initialized when the page loads. Once you get your head around the fact that your plugin has plugins inside it (inception!), we can say it’s quite straightforward — until you need to add new content after the page has already rendered.
That’s exactly what happened on a recent project. We needed to include additional information to the checkout page —but only under certain conditions, after the page was already loaded. To avoid reloading the page or adding an event listener that would stop the checkout process (not the best idea for user experience, specially in the checkout process), we opted to use Javascript to add the dynamic content without reloading the page. So we fetched the data, injected into the Twig template, and… nothing happened. The expected JavaScript behaviour didn’t kick in.
After some time scorching StackOverflow and googling for answers, we found out what was missing. You have to manually call:
window.PluginManager.initializePlugins();
any time you add DOM elements dynamically and want Shopware to initialize JavaScript behavior on them. But this will cause all your JS plugins to re-initialize (not desirable).
So you can determine which DOM element you want to re-inialize and pass it as an argument in the method – so only that bit of the page will be reinitialized, without reloading or reinitializing the whole page.
const jsContainer = DomAccess.querySelector('.class-where-you-want-to-inject-js');
window.PluginManager.initializePlugins(jsContainer);
This is somewhat overlooked in Shopware’s documentation – there is an article on overwriting existing JS, but not specifically adding content after the page is loaded.
So if your JavaScript works on page load but fails when injecting new elements, you’re probably just missing this call. It’s a simple fix, but one that’s not obvious if you haven’t run into it before.
Other articles from this category