Thursday 19 February 2015

jQuery plugin for content shared by multiple pages

Often content will appear in multiple pages in your website. For example, headers and footers will be the same on all pages. This is easily done using PHP, but it can also be done using jQuery, in fact better. Below is a Twitter Bootstrap page. As you can see I have a nav, a header and a footer. All of which have nothing in them, but I do have 3 things in my armoury:

  • A directory called 'includes/' which contains navbar.html, header.html and footer.html. They hold the content I need to fill these empty elements.
  • A plugin called 'include.plugin.js' (shown in red) which applies external file content to these empty elements.
  • A 'custom.js' (shown in red) which can be loaded on every new page I create.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">  
    <title>jQuery includes</title>
    <link href="bootstrap-3.3.2-dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/custom.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <nav class="navbar navbar-default"></nav>

    <div class="row">
      <div class="container">
        <header class="col-md-12"></header>
      </div><!-- .container -->
    </div><!-- .row -->  

    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <p>Use the navigation.</p>
        </div>
      </div><!-- .container -->
    </div><!-- .row -->
   
    <div class="row">
      <div class="container">
        <footer class="col-md-12"></footer>
      </div><!-- .container -->
    </div><!-- .row -->

    <script src="jquery/1.11.2/jquery.min.js"></script>  
    <script src="bootstrap-3.3.2-dist/js/bootstrap.min.js"></script>
    <script src="js/receiveget.plugin.js"></script>
    <script src="js/include.plugin.js"></script>
    <script src="js/custom.js"></script>
  </body>
</html>

Now let's have a look at the include.plugin.js. It does a simple load, but while we're waiting for the content to come through a loader gif is put inside the calling element. This is overwritten when the content arrives.
(function($)
{
    $.fn.extend(
    {
        include:function(includefn)
        {
            $(this).append($('<img>',{src:'img/loading.gif'}));            
            $(this).load(includefn);
        }
    });
})(jQuery);

Finally, custom.js which contains the calls we need.
(function()
{
$('nav.navbar.navbar-default').include('includes/navbar.html');
$('header').include('includes/header.html');
$('footer').include('includes/footer.html');
})();

No comments:

Post a Comment