-
-
Notifications
You must be signed in to change notification settings - Fork 50
Bundling strategies
There are some different strategies when it comes to using bundles. This will discuss some of them.
Define a bundle containing all of your sites javascript (even js that's only used on particular pages) and render it in your _layout.cshtml
.
bundles.Create("site-bundle", //bundle name
new JavaScriptFile("~/Js/Bundle1/site.js"),
new JavaScriptFile("~/Js/Bundle1/somevendor.js"),
new JavaScriptFile("~/Js/Bundle1/pageA.js")
new JavaScriptFile("~/Js/Bundle1/pageB.js"));
This results in a larger bundle for the browser to load initially, but it can be cached as you navigate from page to page, which means navigation should be speedier.
Define a common bundle, which will include files you want to be loaded on every page.
bundles.Create("site-bundle", //bundle name
new JavaScriptFile("~/Js/Bundle1/site.js"),
new JavaScriptFile("~/Js/Bundle1/somevendor.js"));
Then render the common bundle in _layout.cshtml
<script src="site-bundle" type="text/javascript"></script>
Now define seperate bundle for each page:
bundles.Create("pageA", //bundle name
new JavaScriptFile("~/Js/Bundle1/pageA.js"));
And render the page specific bundle within each pages razor file:
PageA.cshtml
:
<script src="pageA" type="text/javascript"></script>
Don't define a site / common bundle or render anything in the _layout
.
Just create a bundle for each page of your site, including all of / only the javascript that the page needs.
bundles.Create("pageA", //bundle name
new JavaScriptFile("~/Js/Bundle1/site.js"),
new JavaScriptFile("~/Js/Bundle1/somevendor.js"),
new JavaScriptFile("~/Js/Bundle1/pageA.js"));
There are pro's and con's to each approach, so it's up to you around which strategy you want to use.
Remember you can always use different strategies for particular pages, by making them use a different _Layout
.
For example, perhaps your registration page, you want it to load in the quickest possible time for new visitors, who are unlikely to have anything cached. So you can use a specific layout for the registration page _RegistrationLayout.cshtml
that doesnt define any common / site bundle, and then in Registration.cshtml
render a page specific bundle only. For the rest of your pages using the default layout, you could use the Common bundle plus page bundle approach.