Best practices on a "loading" widget.

Best practices on a "loading" widget.

I'm developing a modal loading widget that could be applied to the document as a whole, or a specific element on the page (e.g. an Ajax grid)

Using the $.widget would end up looking something like this:

  1. $(document.body).loading();

  2. ... <activity> ...

  3. $(document.body).loading('destroy');

Now, I have a case whereby I'm trying to clear out any blocking loading widgets on the document body, but the loading widget may not have been initialized.  As I'm getting an error, its seems that I'm not following some aspect of best practices on this.

I could think of a few different solutions.  One would  be try {} catch {}, which seems like a poor idea.

Another would be to test for initialization:

  1. var instance = $.data( document.body, 'loading' );
  2. if ( instance ) {
  3.       instance.destroy();
  4. }

But I suspect that directly accessing the widget instance isn't the best approach either.

Does anyone have any suggestions?