Search code examples
javascriptjqueryjquery-load

include() like function in javascript


objective

I need a function that simply takes all the code from another file and pastes the code in the calling file.

possible solution

a function that works like the include() function in PHP.

reason

When I had hosting, I used the php function include("filename.html") to include things like headers and footers, in all the files on the website. This made life a lot easier!

Now I don't have hosting, because I am working on another site, and I am using Github Pages and thus, I can't use PHP. I need to use only HTML, JS and jQuery etc. So, I need a function that simply takes all the code from another file and pastes the code in the calling file.

Already tried

  1. load() in jQuery.

    <pre><script>    
    $(document).ready(function(){
        $("#topbar").load("menubar.html");
    });    
    </script></pre>
    
  2. This question. I tried the accepted answer, but that didn't work for me.

Kindly help me with this issue.


Solution

  • You should consider setting up a build environment where you can compile your content locally before publishing it. This way, you can organize your code in different files (like in your case, with a header/footer that will always be included with different content files), compile locally to have the files automatically combined into a publish directory, and upload that instead.

    This way, instead of e.g. sending 3 requests for a header, content and footer file, the header and footer are pre-compiled into the content file which can then be served with 1 request.

    Personally I use Grunt as a build tool for purely static sites, together with a concatenation task (such as grunt-contrib-concat). There are several tutorials on the Grunt website, but you can see an example of how to configure a task for your specific problem here:

    https://stackoverflow.com/a/12749861/351435