cdnicoll
cdnicoll

Reputation: 584

Document ready, is there a limit?

I'm working on a templated site which loads a header, footer and dynamic body. I have a class in which I specify what scripts will be loaded depending on the current page, and the user logged in status. I've written a few jquery plugins, and when a page loads I need to call on the plugins via

$(document).ready(function() { // $().thePlugin() });

I'd personally not have more than a single doc ready script on each page that called this, but I see no other option. Is it bad practice to have 4 or 5 scripts calling that function?

Upvotes: 1

Views: 529

Answers (3)

cletus
cletus

Reputation: 625097

Having multiple ready() blocks on the one page is fine. In fact, it's exactly set up so you can do this. The old method (usually used on load() events) did things like:

window.onload = function() {
  ...
}

but that quickly broke when multiple scripts both assigned load() handlers, which led to:

function addLoad(handler) {
  var current = window.onload;
  if (current) {
    window.onload = function() {
      current();
      handler();
    }
  } else {
    window.onload = handler;
  }
}

Well, there was a little more to it than that but that was the basic principle. jQuery essentially takes care of that boilerplate for you so your event handlers don't clobber each other.

Multiple ready() handlers makes your code easier to maintain and probably easier to read. If you're only doing a few then don't even worry about it. If you get up to hundreds (on the same page) then maybe it's time to rethink.

The alternate approach is to write your markup to a buffer in PHP and all your ready() code to another buffer and at the end you can write out those buffers in whatever order you like. You could effectively combine your ready() handlers into one this way.

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630429

It's not a function you're calling, but an event you're hooking up to...there's nothing wrong with doing it multiple times, but don't depend on them firing in a certain order is all.

Side tip, this is an equivalent shortcut:

$(function() { $().thePlugin(); });

Also, if these are common to all your pages, move them to an external .js file. If there's not a lot going on, then a few selectors that don't find anything won't hurt. It's just a tradeoff based on of what % of the code you're using what % of the time.

Upvotes: 0

Urda
Urda

Reputation: 5411

If you are using PHP, have you looked into using the PHP autoloader?

http://php.net/manual/en/language.oop5.autoload.php

This may help you cut down requests, and allow last chance includes.

Upvotes: 0

Related Questions