MrMyth
MrMyth

Reputation: 67

Can you "nest "JQuery loading of HTML content?


Is it possible to "nest" content from multiple HTML files with JQuery.load() ?

I want to be able to have all the HTML content in the top level "content" div.
My code example looks like this:


load.js - "firstLayer" loaded into "content" div

$(function () {
    $('#content').load('/first.html #firstLayer', true)
    $('#firstLayerContent').load('/second.html #secondLayer', true)
})

first.html

<div id="firstLayer">
    <div id="firstLayerContent"></div>
</div>

second.html

<div id="secondLayer">
    <p style="font-size: 100px;">Hello world</p>
</div>

Upvotes: 2

Views: 64

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337626

Yes, you can**. You just need to ensure that the second load() call executes after the first so that the #firstLayerContent element is guaranteed to exist at the point you try to put content within it. To do that use the callback argument:

jQuery($ => {
  $('#content').load('/first.html #firstLayer', () => {
    $('#firstLayerContent').load('/second.html #secondLayer');
  });
})

** But be very careful with this pattern, as you can easily cause a drain on server resources by making lots of small requests for partial data. In nearly all cases it's more performant to make a single, larger request which retrieves all required data from the server and process it on the client.

Upvotes: 1

Related Questions