Denys Wessels
Denys Wessels

Reputation: 17039

Loading jquery in MVC 4.0 master page

In the <head> section of my _Layout.cshtml(master page) file I have the following reference to minified jQuery:

<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>

After adding this line I can now use jQuery in everyone of my pages which reference the master page which is great.What I would like to know is how often is the loading of the jQuery file performed?Will it be done everytime a page is loaded or only once when the first page of the website is loaded in the browser?

Upvotes: 0

Views: 708

Answers (2)

Mox Shah
Mox Shah

Reputation: 3015

Instead, create a bundles for your javascript files in App_Start\BundleConfig.cs file, add bellow code. it will load all jquery- prefixed files where the remainder is a version number e.g. jquery-1.10.2.js

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

or

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/*.js"));

this will load all the .js files from scripts folder.

To load above bundle, go to your _Layour.cshtml (your master page) and render as bellow

@Scripts.Render("~/bundles/jquery")

UPDATE

Same way you can create bundle/minification for your custom javascript file.

set this flag true in your BundleConfig.cs file for minification of javascript files

BundleTable.EnableOptimizations = true;

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337570

The file will be loaded in to the browsers' cache upon first load. For every subsequent request it will be read from the cache to reduce bandwidth requirements and improve speed.

If you really want to improve performance, you can load jQuery.js from a global CDN, such as Google, which has the advantage of being fast, and due to it's widespread use it's highly likely that someone already has jQuery in their cache from this location.

I would also suggest using a newer version of jQuery as 1.8.2 is quite old now. If you need legacy browser support (IE9 and lower), use 1.11:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

Otherwise you can use the smaller and more efficient 2.x:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

Related Questions