With jQuery, you can load not just the contents of a URL, but a specific CSS selector from within that URL. It’s like this.
$("#area").load("something.html #content");
That finds the content in the file something.html
within the element with an ID of content
and puts it on to the current page, inside the element with an ID of area
.
But let’s say that something.html
is actually extremely similar to the current page. Your goal is actually to replace #area with #area from something.html
. So you do this:
$("#area").load("something.html #area");
But that’s problematic, because now you’ll end up with:
<div id="area">
<div id="area">
<!-- stuff -->
</div>
</div>
And whatever triggered that action, if you did it again, would lead to even more nesting (bad).
The simple solution is to just grab all the contents of #area, rather than #area itself.
$("#area").load("something.html #area > *");
And the World’s simplest (not feature full) demo:
This is particularly useful when:
- You are Ajaxing a site as a progressive enhancement, so each URL isn’t just a fragment of data but a whole page that otherwise stands on it’s own (and pages are of similar structure to each other).
- You don’t want to add markup to the page like
<div id="inside"></div>
just to get around this issue.
Thanks to Anthony Harris.
Nice and simple post , I remember one of your screen-casts on ajax load , that’s really great!
I really love your screen-casts ….. too little of them these days Chris! i miss them all!
me too. I miss having a weekly dose of screencasty goodness from css-tricks >< lol
Oftentimes when you are doing something like this, the root element (#area, in your example) has potentially different attributes, making the “#area > *” not quite right.
It’s for this reason that I have a “loadReplace” method that does the work for me :)
“With jQuery, you can load not just the contents of a URL, but a specific CSS selector from within that URL. It’s like this.”
You mean DOM selector, right?
Anyways, good tip, I had this problem myself before and this is an elegant solution.
I mean CSS selector. jQuery uses Sizzle which is a selector engine that uses CSS selectors, so that’s what you use after the URL in the load function.
thanks for tour article
Just as a note. This does not allow you to load content from an external page. Found that out the hard way.
AJAX enforces a same domain policy and will only load content from the same address as the the page it’s on. To get around this you can use a server-side language like PHP to load the page and then echo/print it back out (basically a proxy)
That’s really sweet. Watching my pages reload the same backgrounds over and over is annoying. Thanks!
Loading a whole page, but getting only a part of it. Although this is possible with jQuery, I won’t use it ever. I would load only the data I want to. Any extra data loading sounds like a bad architecture to me..
Agree
aggree with you!
I understand what you mean, but it’s a little hard to argue things like this without any context. Such is the nature of isolated tips like this. This might be 100% perfect for some specific project.
@Chris: as you said, this tip is usefull when you have to edit/change/add functionality to an existing behavior, but i wont never *plan* this feature while making a project
That’s what I’m saying.
If you need to load contents from a page which you show in browser as a “regular” web page, you’d better insert some server side logic in it which will filter the content when there’s XHR (it’s actually one if block in most cases).
But loading a whole page via XHR when you need only one or two blocks from it, well, this is counter logical. You load extra content instead of saving it and reduce response’s size, which in turn will speed up the loading.
hristo is right! why load an entire page if you only need parts of a page? it’s great to know that’s possible, i didn’t know that until now!
Please note that this behavior do load the entire page, and then jquery parse it to return just the selector.. so, i think this is a trick is a “quick’n’dirt” solution, definitely waste bandwith and browser resources ;)
The only issue I can see with this is SEO. Search engines will not load this content to my best knowledge.
When you have server side includes the search engine gets back the HTML in it’s entirety.
With the above jQuery method, the browser is responsible for getting that HTML.
I could be wrong but I think this would be bad for SEO.
I don’t think so. Unless I’m looking at it wrong, you could have a normal website set up with all of the pages linked with normal navigation that search engines would have no trouble spidering.
This script just adds some progressive enhancement on top of that, so you don’t have to load the entire pages, but just the content. But without the script, it degrades to a standard website.
absolutely. good for users, too, not just SEO.
Looks good, but you could probably just change the # and add a hidden class, that way it will only have to load each page once and still switch between them.
function changePage(page) {
if( $(page).css(‘display’) === ‘none’ ) { //If loaded and hidden
$(page).fadeIn(‘fast’);
}
elseif( $(page).css(‘display’) !== ‘block’ ) { //If not loaded
$(page).load(page+”.html #”+page+” > *”);
}
// Do nothing if already loaded and active
}
There’s an example of the functionality, although not very good quality code.
Whoops, this after [$(page).fadeIn(‘fast’);]
$(‘.active’).removeClass(‘active’).fadeOut(‘fast’);
$(page).addClass(‘active’);
This still stumps me. Not necessarily the article which I think is superb, but the need for a hash.
I think I have mentioned this before but why not do something like this?
Because of SEO. See https://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/ for more info on that.
Ah ha, so nothing to do with functionality but everything to do with crawlers and search engines.
Hmmm, crawlers generally use the href attribute of links to index sites. So technically using a hash for each might cause more problems right?
Having the page that just loaded show up in the URL bar doesn’t necessarily mean it works better for SEO, as most crawlers I have encountered search out the href attribute and follow that from the HTML.
The only real reason I can see in using a hash for the URL would be for the end user.
The reason the hash is there is actually not for SEO, its to maintain the use of the back button. Rule #1 when Ajaxing a site is to not break the browser’s functionality, which your code would do by making the back button load the wrong page.
Say I was at google, and ended up clicking onto a site with your code, then I clicked some dynamic content links. If I then wanted to go back to some previous content on your site and hit my browsers back button, I’d be back at google.
By making a.click() trigger a hash change, we update the browsers history with that hash. Then we listen for the hash change event on the page and when you see it change based on either a clicked link or a history navigation action, the site will act in a consistent manner.
I sent this trick to Chris because of the video Jan-Marten mentioned – you should definitely check that out. The difference between this method and Chris’ method from that video is that his requires a #guts div to contain the content you’re trying to load. This method does not, and allows you to write purely semantic HTML without adding superfluous elements for the sake of the javascript.
I copied and pasted all the code into my CSS stylesheet and it doesn’t work. This site is about CSS Tricks right? ;P
I kid, it looks like a pretty simple approach, like it.
Once again, very timely. I’m building a website and have been using the Dynamic Page/Replacing Content (https://css-tricks.com/dynamic-page-replacing-content/) item to have a site that loads the background, navigation, etc only once and then loads the content of the rest of the site independently.
But I’ve run into trouble when the content I’m loading has other jQuery goodies like tabs or a content slider in it. Somehow it all turns into a train wreck and stopped working. Maybe this technique will solve that…
/fingers crossed
I’m working on an app that will switch content on the frontpage (a custom PC app), a feature like this could be just what I need. ;)
I’ll keep this tab open just in case.
Very helpful. Remember to use a cool loading circle before content loads.
I’m also very glad to see that you enjoy bacon!
Cool article
Wouldn’t it be better to use $.get in this kind of situations?
If you needed to pass parameters or something, sure, but I don’t think it’s automatically better. They all use $.ajax internally anyway I’m pretty sure.
Really cool but I’m wondering, how does this work in terms of SEO? When the page is crawled for the links inside, does it recognize them as links?
Yes.
Cool
I get this as quick solution while working with jQuery and i think it’s quite useful trick, cause when you get into situation where nothing else works, this can be real savior. It’s something you achieve with experience.
“With jQuery, you can load not just the contents of a URL, but a specific CSS selector from within that URL”…
Although, lets not forget that AJAX rocks because it can make your pages work better and faster for the end user. If you just load an entire page using AJAX, only to take one division from that massive page, you are wasting everybody’s bandwidth and time!
Not to say this isn’t a great article though as it is a really handy trick – but please don’t do anything crazy with this knowledge.
Another solution would be to have two div’s.
Then when loading via JQuery
$("#1").load("something.html #2");
Hmmm …
So try this in IE $(“#target”).load(url+” aside#All-Content > *”);
Best regards! P.S. Load() function doesn’t works fine with HTML 5 tags in IE!
can we load and add animation afterward?
like
$(“#area”).load(“something.html #area > *”).show(“slow”);
Pass function as second optional parameter:
Chris, thanks for this. I’m working on a project with some pretty vanilla Ajax (pretty newb at Ajax) and this is just what I was looking for to make it better. I’m encountering issues when I want to run JavaScript from the ajaxed page – could your idea here be part of a solution?
everyone keeps saying to avoid loading the whole page if you only need a small part. The question I have is:
What is the best way to do this? Post a variable to test for in php? Seperate the area you need into a new file that is included in the original file (server side) and send the ajax request there? Or none of the above…
I have a page/application that relies much more heavily on this jquery function than I would like. If I can get this fixed up to use less bandwidth it would be great, I just dont know the best way to get it done. Thanks for any advice in advance.
sorry about the bad link. here is the right one:
Bless Your Letter Art
I’ve done this for some time ago just for fun.
Still works when javascript’s not activated.
The only issue is the contact form whan loaded via ajax.
Pretty cool, though I just found out the hard way that it doesn’t actually “grab all the contents of #area”, but instead selects every *DOM node* that is matched by the “> *” expression. So, for instance, if your markup goes like “Lorem Ipsum Content”, only “content” will be selected.
Pretty logical when you think about it, but it took me a while to figure this out.
Sorry, meant <section id=”area”>Lorem Ipsum<p>Content<p></section>.
is there a way to apply this to a page that doens’t end in .html?
for instance, i would like to display the most recent div after a page reload, but i’m using wordpress and the url looks like so:
http://civitasinc.com/2013/philosophy/#ideas
so, I would like to display a div with the target of #ideas if the page reloaded or someone just happen to copy paste the url into another browser…
thanks!
Good one.
From where you can get a ” something.html ” file.