Magento 2 module to run scripts such as GTM off main thread using partytown.
Performance Benefits
⚠️ Warning: Please note that this module is still in development and has not been tested fully. Partytown is not a one-size-fits-all solution and depending on which third-party scripts you are loading and how you may need to adjust the configuration. For example if new tags or scripts are added to GTM you may need to adjust the Load Scripts on Main Thread configuration. See the partytown documentation for more information.
composer require rossmc/magento2-partytown
After disabling the module, you can use the configuration option to Unregister Partytown Service Worker. This helps remove the service worker from user's browser to prevent the cached service worker from interfering.
Once you have enabled and configured the module you can load scripts with Partytown off the main thread by adding type="text/partytown"
to the script tag.
See here for more information on how to use partytown.
GTM for example:
<script type="text/partytown">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->
Note: Forwarding Events And Triggers must be configured for GTM to work properly.
You will see your scripts loading with the updated type="text/partytown-x"
tag in the source code.
In the Chrome DevTools Network tab you will see the gear icon by the file name to indicate the GTM script was loaded by the partytown service worker.
And in the Sources panel, you will see the partytown threads.
If you need to override the configuration or change the partytown version you can do so by overriding them in your project. To regenerate the partytown files you can run the following commands:
npm install
npm run copylib