Saturday, September 21, 2013

Including a file via Javascript (with jQuery)

When the website you're developing is big enough it will be most annoying to copy paste the "header" and "footer" code parts every time on every page. If you are using a server-side language like PHP you really don't have a problem - just do

<? include('header.html'); ?>

But what if the site you're developing has very many pages but they are all really simple - to the point that you can't really justify using a server side language? Common issue.

With javaScript you can't really include a file but you can "load" a file into a div, paragraph, or whatever else. When it comes to javaScript, I ALWAYS use jQuery for web-page development. So we need to include that first.

<html>
    <head>
        <script type="text/javascript" src="inc/js/jquery.min.js">
        </script>
        <script>
            $(function(){
                  $("#headerDiv").load("header.html");
              });
        </script>
    </head>
    <body>

        ...
        <div id="headerDiv"></div>

    </body>
</html>

Simple, clean, nice, makes me happy... if it is not working for you I'm going to guess that you are using Chrome and developing locally. It's a Chrome thing - they don't let you do that for security reasons. Just upload your file to the server and test it out - it will work like a charm (in Chrome, too).

What's even better, you can keep your site menu in a separate file as well - this way if the customer requests some changes or asks to add a menu item or you simply made a mistake - you will only have to edit the menu file instead of each and every of the 100 pages you have.

You can argue that the menu might be slightly different on every page - the current menu item needs to be highlighted / different from others. also not a problem - include your menu file, then use .addClass().

I always use Twitter Bootstrap as well, so for me i just do .addClass("active") on whichever <li> I need. You WILL have to add id-s to each and every menu item to do this correctly. It's a really small trade of in time compared to what you would spend if you weren't doing things in this sort of way.

No comments:

Post a Comment