Insert html file via javascript

Asked

Viewed 3,746 times

2

Look I would like to load the "head" part of my html into just one file and then called into html via java script.

Today I have following:

Header

inserir a descrição da imagem aqui

File where you would like to insert the header

inserir a descrição da imagem aqui

I need to enter the same via javascript because I will use the same header in several places.

I searched the Internet and got back something like

 $("#header").load("index.html");

But I will not insert in a div but in the html itself.

  • Need to be specifically html? would be simpler to do this with php :D

  • Unfortunately yes Alvaro, we will not use anything in the project other than JS/HTML and CSS;

  • You can try with <object data="html/stuff_to_include.html"> &#xA; Your browser doesn’t support the object tag. &#xA;</object> but it will only work if the files are on a server. Or you can use an iframe

  • The ideal was to carry only the <head></head and not the <!DOCTYPE html> and the opening of <html>.

  • 1

    Another thing is that Ajax only works in server environment.

  • You should use a programming language, any one, to assemble these Htmls for you. How does the Jekyll, for example.

Show 1 more comment

4 answers

2

You can use the method .insertBefore Javascript to create a tag <head> before the body and pull via Ajax the contents of the other file and send into that <head>, but it is necessary to make some considerations:

When you nay inserts the tag <head> directly in HTML, the browser automatically corrects and inserts <head></head> in the document. Thus, when dynamically inserting a tag <head>, the document will be tagged <head> duplicates (one created by the browser and the other inserted via .insertBefore).

Then you can ask: "why create a <head> if the browser already calf?". Like I don’t know if all browsers do this, it would be a precautionary form.

Put it in the file head.html only the content of <head>, without the tags <!doctype> and <html>. That’s because the tag <!doctype> defines the document type of the page and cannot be dynamically inserted. Hence the structure of the index.html would have to be:

<!DOCTYPE html>
<html lang="eng">
   <!-- AQUI SERÁ INSERIDA A <head> -->
<body>
   CONTEÚDO
</body>
</html>

And the archive head.html only the content of <head>:

<meta charset="utf-8">
...
<link href="arquivos/dashboard.css" rel="stylesheet">

Another point is that if you want to use Ajax, it will only work in HTTP protocol, that is, in a server environment.

Considering the above points, a solution using Javascript Ajax (no need for jQuery) is suggested below:

document.addEventListener("DOMContentLoaded", function(){

   var novo_head = document.createElement("head"); // cria o nó <head></head>
   var htMl = document.querySelector("html"); // seleciona o elemento html
   htMl.insertBefore(novo_head, htMl.childNodes[0]); // insere o nó <head></head> antes do body

   var http = new XMLHttpRequest(); // cria o objeto XHR
    http.open("GET", "head.html"); // requisita a página .html
    http.send();
    http.onreadystatechange=function(){
      if(http.readyState == 4){ // retorno do Ajax
         var head = document.querySelectorAll("head"); // seleciona os <head>
         // insere a resposta no primeiro <head>
         // o índice [0] significa o primeiro elemento
         // o replace é para remover as tags <head> e </head> da resposta
         head[0].innerHTML = http.responseText.replace(/<\/?head>/g, "");

         // remover a segunda tag <head> do DOM se existir duas,
         // para que não haja tags duplicadas
         if(head.length > 1) head[1].remove();
      }
   }
});

How the code already creates the tag <head> with document.createElement("head"), it would be interesting that the file .head.html did not also have the tags <head> and </head>, that is, only the internal HTML of <head>. So you can delete from the code the .replace in http.responseText.replace(/<\/?head>/g, ""); leaving only http.responseText;.

If you’re gonna use jQuery

If using jQuery, you can use the function $.get sent the return to the tag <head> created with the method .before().

In the case of jQuery, there is no need to worry about tag duplicity <head>, because even if the tag is added by the browser, jQuery does not duplicate it.

The structure of index.html would be (carrying the jQuery):

<!DOCTYPE html>
<html lang="eng">
   <!-- AQUI SERÁ INSERIDA A <head> -->
<body>
   CONTEÚDO
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
   $(function(){

      $.get("head.html", function(data){
         $("body").before("<head></head>"); // insere o <head> antes do <body>
         data = data.replace(/<\/?head>/g, "");
         $("head").html(data); // insere o retorno do Ajax dentro da <head>
      });

   });
   </script>
</body>
</html>

As stated, the .replace(/<\/?head>/g, "") is to remove from the return tags <head> and </head>, but even if the return comes with these tags, the browser fixes, however I put the replace as a precaution, because I do not know if all browsers do this automatic correction. But the ideal is that the return comes without these tags, as said also.

1

Leave in your external file only the internal contents of <head> and use the <link rel="import" href=""> to make the include.

<!DOCTYPE html>
<html lang="en-US">
    <head>       
        <link rel="import" href="/head.html">
    </head>
</html>

Reference

  • This one works locally, or has to put on the server?

  • you mean another domain?

  • It can be tb rss. I wonder if we can test locally and include an html in another one like this. It’s just out of curiosity

  • 1

    Without a server the browser can block

  • It would be interesting to put a link on the browser compatibility. But my question is whether I would need to have some script to manipulate import content. Would it work as a PHP include? I ask because of this article.

0

Your application is HTML and pure javascript? will not utlizar anything server side? if it is, create the header file. with the header’s separate content or add it via INCLUDE from the language you are using,

Advice, usually leave Header and Footer on the page, and change their content, so you would create a "layout.html" with the structure.

<!DOCTYPE html>
<html lang="en">
    <head>

    </head>
    <body>
       e aqui você coloca os conteudos das suas paginas
    </body>
</html>

can easily use jquery because it will have the Body tag, can do

<body>
 $("#header").load('paginaativa.html');
</body>

-1

Try to do that!

<head id="header">

</head> 


<script type="text/javascript">
   $(document).ready(function(){
      setTimeout(function(){
        $("#header").load("header.html");
    },0); });
</script>

Browser other questions tagged

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