Using a CDN
The follow code replaces the local jQuery bundle with a CDN jQuery bundle.public static void RegisterBundles(BundleCollection bundles) { //bundles.Add(new ScriptBundle("~/bundles/jquery").Include( // "~/Scripts/jquery-{version}.js")); bundles.UseCdn = true; //enable CDN support //add link to jquery on the CDN var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"; bundles.Add(new ScriptBundle("~/bundles/jquery", jqueryCdnPath).Include( "~/Scripts/jquery-{version}.js")); // Code removed for clarity. }
In the code above, jQuery will be requested from the CDN while in release mode and the debug version of jQuery will be fetched locally in debug mode. When using a CDN, you should have a fallback mechanism in case the CDN request fails. The following markup fragment from the end of the layout file shows script added to request jQuery should the CDN fail.
</footer> @Scripts.Render("~/bundles/jquery") <script type="text/javascript"> if (typeof jQuery == 'undefined') { var e = document.createElement('script'); e.src = '@Url.Content("~/Scripts/jquery-1.7.1.js")'; e.type = 'text/javascript'; document.getElementsByTagName("head")[0].appendChild(e); } </script> @RenderSection("scripts", required: false) </body> </html>
If the script element that results from the @Script.Render
directive fails to load jQuery,
then the jQuery object remains undefined. In such case, the script above dynamically adds
a new script element, which explicitly refers to the jQuery file hosted on our server, instead of the CDN.
Bundles set the HTTP Expires Header one year from when the bundle is created
· 1.
var jquery = new ScriptBundle("~/bundles/jquery");
·
jquery.Include("~/Scripts/jquery-1.8.1.min.js");
·
bundles.Add(jquery);
2. · bundles.Add(new StyleBundle("~/bundles/css").Include(
· "~/Styles/site.css"
· ));
bundles.Add(new StyleBundle("~/allStyles").IncludeDirectory("~/Styles", "*.css"));This results in all .css files in the Styles folder being bundled in alphabetical order so doesn't differ from the previous wildcard example. However, the IncludeDirectory method offers an overloaded version that allows you to include subfolders in the search for matching files:
bundles.Add(new StyleBundle("~/allStyles").IncludeDirectory("~/Styles", "*.css", true));
0 comments:
Post a Comment