Fixer
Fixer

Reputation: 6095

ASP.NET Master Page and jQuery

I've got a single site.js file which has a

$(document).ready(function () {
    initMenu();
});

and the corresponding MasterPage:

<head>
    <script src="@Url.Content("~/Scripts/jquery-1.4.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/Site.js")" type="text/javascript"></script>
</head>

In the above example initMenu() is required to run on all pages, so naturally the site.js is put in the master page.

However, there are some pages which requires a different set of initialization code so it does not feel to make all pages run the following initialization.

$(document).ready(function () {
        initMenu();
        showGallery(); <-- Problem?
    });

How should i structure the JS references so all pages can share a common initialization and other pages do not?

Upvotes: 0

Views: 229

Answers (2)

Nick Craver
Nick Craver

Reputation: 630349

You can add other document.ready event handlers to the pages that need additional ones, for example this can be in the page that needs the gallery setup:

<script type="text/javascript">
  $(showGallery);
</script>

...would execute your showGallery() function when the DOM is ready. Also, as long as it appears after your previous code, it's sure to run after it. ready handlers will execute in order (unless called via .bind("ready"...) which is different...those happen after, but still in order).

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129792

You can define several functions to be executed at DOMReady. I would simply add the following in gallery.js (or wherever showGallery might be defined)

$(function() {
    showGallery();
});

Upvotes: 1

Related Questions