Some simple jquery use cases for .load()

No technical feature (i.e. coding) under the umbrella of tommygreenfield.com is particularly impressive-Not that I personally have implemented, anyway.* Mainly, because tommygreenfield.com has no function that requires technically impressive code. Still, now and then I feel like learning something new and applying it to the site, whether there’s a “functional” value-add or not.

{ WordPress is, of course, impressive.}

For instance, I considered a hypothetical scenario where I have multiple pages with the same header/footer. An implementation where the same div is copy-pasted one every page would be a foolish one; if I had to make a change, I would need to copy/paste the changes into each hypothetical file. Better would be if the header were it’s own resource and each page looked to the same single resource.

jquery’s .load() function affords this opportunity: Instead of plugging something like this into each page which needs a header…

<div class="inheader" id="name">Back to <a href="../index.html">TommyGreenfield.com</a></div>
<div class="inheader" id="email"><a href="mailto:tommyn.gre@gmail.com">tommyn.gre@gmail.com</a></div>

…We define that in its own html resource and plug this into each page which needs a header:

<script>
$(function loadhedr() {
$( "#header-reference" ).load( "header.html #header-source" );
});
</script>

In this case, needless to say (??), “#header-reference” refers to the div id for each page which needs a header; “header.html” is the new html resource; “#header-source” is the div id within header.html.

Then when we change the html resource we’re referencing, each page which references it will be “updated.”

Another use case: I can load a list of recent entries on this blog into a div on another page (e.g. tommygreenfield.com).

<script>
$(function getposts() {
$( "#posts-reference" ).load( "/blog/index.php #recent-posts-2 li" );
});
</script>

In this case, I just created an empty div on tommygreenfield.com called “#post1″ then load the li elements from the blog’s homepage (contained in #recent-posts-2”) into it. No need to perform any maintenance whatsoever Whenever I add a new post-tommygreenfield.com will always load from tommygreenfield.com/b (the blog).

The only downside to this approach is performance; it takes a moment to load. Another day I’ll see whether I can improve this further 🙂