How to reuse HTML code with pure Javascript?

Asked

Viewed 121 times

-1

I am creating a site with multiple pages and constantly modify my header, is it possible to create a single header and use it on all pages? (preferably with pure javascript)

  • 2

    I don’t think it’s very elegant, I don’t know how much of a gambit is, but the closest thing I’ve seen to today is <object type="text/html" data="outro.html"></object> - That said, almost every page server software (Apache, IIS, etc.) has a proprietary engine for this (without relying on other server side languages, including)

  • 1

    How about using the pjax? :p

2 answers

0

The solution is to put the codes that will be reused in a separate file and load with the method load() Suppose you have this file called main.html:

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="UTF-8">
  <title>Main page</title>
  <sript src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
   $(function(){                  
    $('#commonsection').load('reutilizavel.html');
     // Usa a função load para carregar o arquivo html
   });
    </script>
 </head>
 <body>
     <div id="commonsection"></div>
 </body>

And in the archive that will be reused:

 <script>
 (function($){ //separate scope to keep everything "private" for each module
    //do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>

-2

  • 2

    The problem in the case would be how to style the part of the template that was included, right? I don’t think that’s a good solution.

  • Truth Wallace.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.