Jed
Jed

Reputation: 10897

How to check if jquery package is being referenced

I have an MVC 3 Razor partial page that is dependent on jquery.validate.js and jquery.validate.unobtrusive.js.

Is it possible for the partial page to check whether or not there is, already, a reference to the .js packs?

Since this is a partial page, it's possible/probable that either the _Layout.cshtml or another included partial page has already referenced the .js packs. To avoid duplicate references to the .js packs, I would like the partial page(s) to be able to determine if it needs to add the reference to the packs or not.

Upvotes: 2

Views: 745

Answers (3)

Andrey
Andrey

Reputation: 21285

You can check if jQuery and jQuery.validate are defined and load the script if it's not, but it's not really worth the effort - browsers are caching js files, so if you have two references, it will only download it once.

Upvotes: 1

Craig M
Craig M

Reputation: 5628

The following bit of js code would check to see if the two plugins have been added to the jQuery object.

if (jQuery.validator != undefined && jQuery.validate != undefined) {
    //do something
}

Upvotes: 3

thitemple
thitemple

Reputation: 6059

I'm not sure if this solves your problem, but there's a jquery function called getScript that loads a server script through a get request.

http://api.jquery.com/jQuery.getScript/

As it runs globally it might solve yout problem. You just have to do this:

$.getScript('url.js', function(){
//
});

Upvotes: 1

Related Questions