Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a function just before $(document).ready() triggers

I've attached multiple functions in multiple files to $(document).ready and would like to attach a single function to happen before them as either the first that $(document).ready handles or to independently trigger before the $(document).ready handler.

Is there any way to handle the order of functions that jQuery triggers internally as part of jQuery.fn.ready or to hook in a function that calls just before jQuery.fn.ready.

Is editing jQuery.fn.ready in a 3rd party script safe to do or will it cause horrible knock on effects in other 3rd party plugins (apart from plugins that edit jQuery.fn.ready themselves)

[Edit]:

as an example

$(document).ready(function b() {});
....
$(document).ready(function a() {/* optional setup*/});
....
$(document).ready(function c() {});

function a needs to happen first irrelevant of order, but only gets called on a few pages. I cant guarantee the order of b or c so I cant trigger custom events at the start of b or c to trigger a.

So I would like a generic solution that I can use to forcefully place a at the start of jQuery's internal readyList or hook into jQuery's ready function and edit it safely so it calls a before any of the other functions in readyList.

[Further Edit]

If possible I would rather not have to redesign the javascript code execution order or have to touch any other code apart from function a(). I'm aware restructuring would allow me to get around this problem but I'd rather just write a single function like

$.beforeReady(function a() {});
like image 295
Raynos Avatar asked Nov 04 '10 15:11

Raynos


1 Answers

This would be a time where I would trigger a custom event that all of your other files would bind to, you would only have one ready handler, which would do stuff, then trigger the custom event.

So, somewhere else in your code, instead of using $(document).ready, you would use

$(window).bind('setup', function() {
   //code here...
});

And/or

$(window).bind('loaded', function() {
   //some other code here...
});

And in your one and only ready handler, you'd do something like this:

$(document).ready(function() {
   $(window).trigger('setup');
   $(window).trigger('loaded'):
});
like image 167
Jacob Relkin Avatar answered Oct 10 '22 07:10

Jacob Relkin