Cosmin Cosmin - 1 year ago 102
Javascript Question

Refactor repetitive jQuery code

I would like to refactor the following piece of code from an old project.

$("#foo_div").html('').load('/some/route/', function(){
// ...

$("#bar_div").html('').load('/some/route/', function(){
// ...

$("#baz_div").html('').load('/some/route/', function(){
// ...

What the code does is to make an AJAX call and get some HTML result which will be then appended to the three divs. The result is always the same, so there's no need to have three identical calls.

Is there any way I could rewrite this code in order to run the call a single time, store the output and then append it to the three divs?

I don't want to use "async" so I'm looking for other means to do it.


Answer Source

Select all three elements and call load()

$("#a, #b, #c").html("").load('foo.html', function(){});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download