How to Use AJAX and jQuery for Client-Side Inclusion of Your HTML5 and CSS3 Site - dummies

How to Use AJAX and jQuery for Client-Side Inclusion of Your HTML5 and CSS3 Site

By Andy Harris

AJAX can give you the same effects for your HTML5 and CSS3 that Server Side Includes (SSI) does. The page will look exactly the same but an entirely different method will be used to achieve your goal.

<!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
 <title>csAJAX.html</title>
 <link rel = "stylesheet"
   type = "text/css"
   href = "csStd.css" />
 <script type = "text/javascript"
   src = "jquery-1.10.2.min.js"></script>
 <script type = "text/javascript">
  $(document).ready(function() {
  $("#heading").load("head.html");
  $("#menu").load("menu.html");
  $("#content1").load("story1.html");
  $("#content2").load("story2.html");
  $("#footer").load("footer.html");
  });
 </script>
 </head>
 <body>
 <div id = "all">
  <!-- This div centers a fixed-width layout →
  <div id = "heading">
  </div><!-- end heading div →
  <div id = "menu">
  </div> <!-- end menu div →
  <div class = "content"
   id = "content1">
  </div> <!-- end content div →
  <div class = "content"
   id = "content2">
  </div> <!-- end content div →
  <div id = "footer">
  </div> <!-- end footer div →
 </div> <!-- end all div →
 </body>
</html>

The page content is empty. All the contents are available. A jQuery AJAX call was used to load each text file into the appropriate element.

Here’s the plan:

  1. Import the jQuery library.

    The jQuery library is by far the easiest way to work with AJAX, so import jQuery any time you want to work with AJAX.

  2. Add an initialization function.

    There are many ways to call initial functions in jQuery. It doesn’t matter which mechanism you use as long as it occurs after the page has loaded but before any other JavaScript.

  3. Load each div with the load() method.

    The jQuery library has a load() method that allows you to make an AJAX call and place the document in the indicated element. Use this mechanism on each element in your page.

The same document structure can be used with very different content by changing the JavaScript. If you can’t create a full-blown CMS (because the server doesn’t allow SSI, for example) but you can do AJAX, this is an easy way to separate content from layout.