收录日期:2019/12/11 02:47:55 时间:2010-10-28 14:13:09 标签:javascript,jquery,jquery-load

I'm looking for a way of increasing the performance of my code. Currently I do something similar to this:

$(".div1").load("Page.aspx #section1");
$(".div2").load("Page.aspx #section2");

However, this means I'm having to make 2 GET requests. Is there any way of reducing this to 1 request by doing something like this:

var content = $.load("Page.aspx");
$(".div1").html(content("#section1"));
$(".div2").html(content("#section2"));

Cheers!

Try this:

$.get('Page.aspx', function(data) {
  var dom = $(data);
  $(".div1").html(dom.find("#section1"));
  $(".div2").html(dom.find("#section2"));
});

btw: probably you'll need a holder-element around your sections, because dom in my example holds the first leve of your <body> tag content and find won't find anything on this first level:

<body>
  <div id="holder">
    <div id="section1"></div>
    <div id="section2></div>
  </div>
</body>  

Can you switch to use JSON?

$.getJSON('Page.aspx', function(data) {
    $(".div1").html(data.section1);
    $(".div2").html(data.section2);
});

This would be faster than doing a regular get and traversing the result, albeit you'll need to encode your response from the server.