Last Updated: February 25, 2016
·
3.117K
· jdlich

Include files with jQuery.load

jQuery.load is a useful, cross-editor way to get include files while building static HTML sites. Here's a clean, simple implementation that I like to use:

<div class="include" data-file="header.html"></div>
<div class="include" data-file="sidebar.html"></div>
<!-- etc... -->

<script>
  $(function () {
    $('.include').each(function() {
      $(this).load($(this).data('file'), function() {
        $(this).children().first().unwrap(); // remove the include div
      });
    });
  });
</script>

NOTE: Any <script> tags inside include files must have type="text/javascript" in order to execute properly.

Fix for Chrome

See Local AJAX calls in Chrome.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside