views:

36

answers:

2

I would like to know if this would be possible in javascript: i have an application, mainly developed in javascript. There are ajax calls fetching html content scattered all around the code.

I would like to create an object that listens whenever a load function is being called, and launch a function in that case (like displaying a preloader).

I know there are many load plugins but they all require to add their own code at every place where a load is launched. I would like to keep this separated, as it's easier to maintain.

Is that possible?

+1  A: 
$('document').ajaxStart(function() { /* show loader */ });
$('document').ajaxStop(function() { /* hide loader */ });

Is not really as simple as that, as several AJAX calls could be going on at the same time, so you don't always want for ajaxStop to hide the loader. You'd have to create a little counter that keeps track of current calls, but those are the events you want to hook up, anyway

David Hedlund
A: 

On the face of it, I don't see why not. If you are only using XMLHttpRequest, then you can create your own handler of the XMLHttpRequest's open (and/or send, depending on what you intend to use), do whatever "loading screen" you want there and then call the original method.

You method should also wrap the onload method handler provided by the caller, so it can terminate the loading screen when the document completes.

Guss