2

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.

Thanks.

2
  • Are the // ... codes identical too? Commented Aug 30, 2016 at 20:53
  • Yes, they are identical. Commented Aug 30, 2016 at 21:13

4 Answers 4

11

Select all three elements and call load()

$("#a, #b, #c").html("").load('foo.html', function(){});
Sign up to request clarification or add additional context in comments.

Comments

3

You can use the jQuery.get function to perform this. See https://api.jquery.com/jquery.get/

$.get( "...", function( data ) {
  $("#foo_div").html(data);
  $("#bar_div").html(data);
  $("#baz_div").html(data);
});

Comments

2

Assuming those ids are for divs you can reduce the query to be any div that has an id that ends in _div

$( "div[id$='_div']" ).html('').load('/some/route/', function(){
    // ... 
});

Comments

2

You can just group the ids in the jQuery selector

$.ajax( "...", function( data ) {
  $("#foo_div, #bar_div, #bar_div").html(data);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.