jQuery load with variable, and split into 2 parts?
-
27-09-2019 - |
문제
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.
제휴하지 않습니다 StackOverflow