JavaScript bundling is an optimization technique you can use to reduce the number of server requests for JavaScript files.
Bundling accomplishes this by merging multiple JavaScript files together into one file to reduce the number of page requests.
Enable JavaScript bundling
Magento must be set to production mode in order for bundling to work.
To optimize bundling, set the following settings to Yes:
Javascript Settings -> Merge JavaScript Files
Javascript Settings -> Minify Javascript Files
Static Files Settings -> Sign Static Files
How bundling works in Magento
By default, Magento bundles all JavaScript files and loads them synchronously on every page load.
This means that each bundle is loaded one after the other and causes delays for JavaScript behaviors on a page.
Excluding files
The <exclude> entry in a theme’s etc/view.xml file tells Magento which files it should not bundle.
JavaScript files excluded from bundling are loaded asynchronously by RequireJS as needed.
Do not bundle JavaScript files used for testing or development because these will get loaded on every page.
The following code snippet from Magento’s Luma theme shows the types of files you should exclude in your theme.
Show example
Setting bundle file size
The bundle_size entry controls the file size of the generated bundles.
Setting this to a large number will reduce the number of bundles generated, but the file sizes will be big.
A small number will increase the number of bundles generated, but the file sizes will be smaller.
You want to balance the number of files to download on a page with the size of the data.
A single connection should be around 100kb.
Fine tuning your theme
There are many ways to tune your theme’s etc/view.xml file.
For example, Magento’s Luma theme is configured to work well for all pages, but
by adding or removing items inside exclude, you can maximize browser performance for home, catalog, or product pages.
Follow these steps to help you identify which JavaScript files to bundle for your theme:
Create a blank page with the layouts you would like to tune.
Compare the JavaScript files loaded in the pages with the JavaScript files in Magento.
Use the results of that comparison to build your exclude list.