Reputation: 261
Is it a good practice to have JavaScript (jQuery) code inside an Ajax response. It works, but I feel it is not the best way (and I feel it is a bad design and makes things difficult to debug).
Should all the JavaScript be loaded before the Ajax call to the server is made?
What could be the best way to go about it? A simple example would help!
Upvotes: 0
Views: 578
Reputation: 10210
Javascript code inside AJAX response has a number of issues:
1) Javascript code loading time can not be determined. Don't load js code dynamically from the server. script load property is not well implemented across browsers.
2) Dynamic CSS load/apply on dynamically loaded js can not be synchronous in time, again timing issue.
3) Closure issue- generally response function is child(callback) of $.ajax function, again $.ajax is child of event handler. So better to put js first time of browser load only. You may face closure issues if variables are not properly placed.
So, basically put only response parsing code in function(response){}, like XML,JSON,Text,HTML...
And remember filling heavy code inside callback function is a bad practice.
Upvotes: 4
Reputation: 1074068
I think your engineering instincts are right on the money. Put your code in a JavaScript file, compress/minify/pack it, and serve it once. The browser can then cache it. Limit your ajax calls to retrieving data or markup from the server, rather than code.
...95% of the time. I'd be willing to bet you could justify the odd bit of code-as-payload sometimes, but I haven't had to do it yet.
Upvotes: 2
Reputation: 47375
I think it's okay to have a little, but not a lot, of script code load along with an ajax response.
For example, we use MVC3 and its jquery unobtrusive validation plugin. Some of our forms have partial views loaded via ajax. After they load, in order to get the client-side validation to work again, we have to run this one line of jQuery:
$.validator.unobtrusive.parse('form');
Something like that I don't mind having in the partial view, though it could just as easily come in the $.ajax.success function.
Upvotes: 0