2
\$\begingroup\$

Im creating an single page application with not reload or redirects so I display all my contents with partial view(since im using MVC4 and angularjs ) and modals.

But I came with a situation, and that is that in some cases when i request a view with ajax to the server I need to perform some action(javascript loads) on the view when load but as you know i have to way for the response(the view) to execute this since still not present in the DOM. So I came with this solution. I just develop a method that allows me to wait for a piece HTML with timeouts and recursions and then execute the code when the HTML is render in the view.

//this is actually a service in angular, im just giving an example
    function $WaitFor(selector,callback,timeout)
    {
    var execute = function()
    {
    if(document.Selector(selector) != null)
    callback();
    else
    startTimeout()
    }

    var startTimeout = function()
    {
    setTimeout(execute, 200 || timeout)
    }

    startTimeout();

    }

And indeed the code works, it waits and execute the code successfully when the response(the view) is display. But, is that code ok? is there any another alternative that? And what about performance? Any sugestions/help you can give me??

\$\endgroup\$
2
\$\begingroup\$

Read your framework's documentation

Before you actually do some voodoo magic on your code, I suggest you read your framework's documentation. It's quite impossible that a web framework has not taken into account JS's asynchronous nature. There should be a proper way to do this.

For instance, in Meteor we have the .rendered handler which runs when the template has rendered or rerendered. This is usually where we hook stuff or modify the DOM to the newly rendered template.

Mutation observers

This is one of the new, shiny toys of JS and should be the proper way to do this operation in plain JS. Mutation Observers listen for changes on the DOM and fire assigned callbacks. You can configure them to listen for specific changes on the DOM, like attribute modifications, subtree modifications (adding or removing DOM). As of this writing, current browsers support them already.

Using AJAX? The callbacks!

When there is AJAX, there should be some mechanism to attach handlers to know when the data arrived. Use that instead.

For example, in jQuery you can do this:

$.get('some_resource_url')
 .done(function(data){
   //Do something with the data when it arrives
 });
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I tried with observer but if you look, ie 10 down not supported. Thanks for your first advice, ill search if angular has a such a method. \$\endgroup\$ – Misters Dec 15 '13 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.