The idea is that if I have two HTML pages I can join them, and I can call their methods and the DOM between both pages, without using a controller likePHP
Example:
page1.html
<!DOCTYPE html>
<html>
<head>
<title>Ejemplo</title>
<script>
function FuncionPagina1(){
return "mundo";
}
</script>
</head>
<body>
<h1 id="mundo" class="mundoClass">MUNDO!!!</h1>
</body>
</html>
page2.html
<!DOCTYPE html>
<html>
<head>
<title>Ejemplo</title>
<script>
function FuncionPagina1(){
return "hola";
}
</script>
</head>
<body>
<h1 id="hola" class="holaClass">Hola</h1>
</body>
</html>
How can I join page1 and page2 , and be able to call them with simple access as if I were on the same page ? can call your own and , and if possible even your JavaScript functions.id="mundo"
class="mundoClass"
id
class
Note : It should be noted that the idea is that it be withoutiframe
It's perfectly possible using
load
jQuery , you just have to be careful not to include page 1 inside page 2 which in turn contains page 1, it would be an infinite loop and I really don't know how it behaves. Finally, back on topic:You can even be more specific and define which section of the page you want to load:
and define some action for when the document load finishes:
In HTML you can use
link
and import files. You probably already use it with CSS files to add styles to your page, but you can also use it to import other HTML pages.This method will allow you to use the JS functions of the other page directly (
script
they are executed at the moment of theimport
), and to access the variables of the imported page you will need a couple of lines (move the imported page to a variable , look for the elements in that variable instead of in the DOM itself). Nothing complicated.So, to import one page into another, you would just have to do this:
If the imported page has JS functions, you can call them directly, and to read the variables it would be something like this:
One important thing to note:
import
may not be supported by all browsers, and are governed by CORS rules, i.e. they must have the same origin or allow the page to be imported per page from other origins.Here is an example:
page1.html
page2.html
Don't take all the text and attach it because there are tags that need to be used only once per page, instead take the content in parts.
The first thing is to use the Fetch API on the page where you want to fetch the external resources, in this case an HTML page.
Although the above is possible, I do not consider it a "universal good practice". As for the functions, in certain cases it is best to put them in a file, that is, create a library, and load it on each page that requires the functions it contains.
Regarding HTML tags, in certain cases the ideal is to put the structure in a page and through classes and/or JavaScript manage the logic of, that is, control, when they should be displayed.
Bibliography