Include html in another html file [duplicate] - javascript

This question already has answers here:
Include another HTML file in a HTML file
(41 answers)
Closed 2 years ago.
I have a html "head" template and a navigation template that I want to include in all my other html files for my site.
I found this post:
Include another HTML file in a HTML file
And my question is... what if it's the header that I want to include?
So for example, I have the following file structure:
/var/www/includes/templates/header.html
navigation.html
header.html might look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Test Portal</title>
</head>
In a case like this, can I still follow the example in the other post where they create a div and populate the div via jquery?

Method 1:
I think it would be best way to include an html content/file into another html file using jQuery.
You can simply include the jQuery.js and load the HTML file using $("#DivContent").load("yourFile.html");
For example
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#DivContent").load("another_file.html");
});
</script>
</head>
<body>
<div id="DivContent"></div>
</body>
</html>
Method 2:
There are no such tags available to include the file but there are some third party methods available like this:
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="content.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
Method 3:
Some people also used server-side-includes (SSI):
<!--#include virtual="a.html" -->

Use <object> tag:
<object data="filename.html"></object>

I needed to include many files. So I created the following script:
<script>
$(function(){
$('[id$="-include"]').each(function (e){
$(this).load("includes\\" + $(this).attr("id").replace("-include", "") + ".html");
});
});
</script>
Use div, for example, to put a placeholder for the insertion.
<div id="example-include"></div>
Created folder "includes" for all files I needed to include. Created file "example.html".
It works with any number of includes. You just have to use the name convention and put all included files in the right folder.

Using HTML <iframe> tag.
I have faced similar problem , then I used
<*iframe* src = "b.html" height="*80px*" width="*500px*" > </*iframe*>

For anyone interested in a Web Component approach:
<html-include src="my-html.html"></html-include>
And the corresponding JS:
class HTMLInclude extends HTMLElement {
constructor() {
super();
this.innerHTML = "Loading...";
this.loadContent();
}
async loadContent() {
const source = this.getAttribute("src");
if (!source) {
throw new Error("No src attribute given.");
}
const response = await fetch(source);
if (response.status !== 200) {
throw new Error(`Could not load resource: ${source}`);
}
const content = await response.text();
this.innerHTML = content;
}
}
window.customElements.define("html-include", HTMLInclude);
Note that it is possible to do some nice things with a shadow DOM to make sure styling of loaded content does not influence the outer page.
The above code is pretty "modern" JS and you might not want to use the above code directly without some polyfills/babel transpilation.

This is similar to another custom tag solution, but this one uses the text between the opening and closing tags as the include path/url. The other solution uses the src attribute instead.
<html-include> ./partials/toolbar.html </html-include>
The element implementation's a little trickier:
# -- ./js/html-include.js --
class HTMLInclude extends HTMLElement {
constructor(src) {
super();
this.attachShadow({mode: "open"});
if (src) {
this.textContent = src;
}
setTimeout(() => this._load());
}
async _load() {
let src = this.textContent.trim();
if (!src) {
throw new Error("URL missing between <html-import> tags.");
}
let rsp = await fetch(src);
if (rsp.status != 200) {
throw new Error(`Failed to load file (${src}) for <html-import>.`);
}
this.shadowRoot.innerHTML = await rsp.text();
}
}
customElements.define("html-include", HTMLInclude);
The setTimeout() was necessary because this.textContent, if accessed too early, can include all the preceding text of the page (seen on Chrome/Chromium). Deferring the access fixes that.
This is what it looks like incorporated in a page:
<html>
<head>
<link rel="stylesheet" href="./css/index.css">
<script type="text/javascript" src="./js/html-include.js"></script>
</head>
<body>
<html-include> ./partials/toolbar.html </html-include>
<html-include> ./partials/side-menu.html </html-include>
<html-include> ./partials/statusbar.html </html-include>
</body>
</html>
CSS styles should be properly applied to the newly imported HTML.
This element can also be created from JS by passing it the URL to the import file.
let wgthost = document.getElementById("tgt");
wgthost.appendChild(new HTMLInclude("./partials/mywidget.html"));

Related

My Javascript file and jQuery aren't linking to my html file (everything is in the same folder and there are no typos)

I have just started coding and I have encountered a problem that seems very obvious. I wrote an HTML code in an HTML file and a CSS code in a CSS file. I have placed both in the same project folder.
To animate my website, I decided to write a Javascript code in a .js file using jQuery. I downloaded the latest version of jQuery into that same folder as all my other files of that project.
The CSS linked just fine, but not the Javascript. (I needed some text in Russian, so I followed the instructions from an answer in this forum). I am using Atom.
Heres my code (the file is long, so I won't include the full contents, just the javascript element... I literally made one to test it out but nothing seems to work) :
<!DOCTYPE html>
<html lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Language" content="ru">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jquery-3.3.1.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div class="out"><p>Test</p>
</div>
</body>
</html>
and here is what i wrote on main.js to see if it works :
$(document).ready(function() => {
$('.out').on('mouseover', ()=>{
$('.out').hide();
});
});
So as you can see I am trying to make this part hide when the mouse goes over it. I also tried with 'click' and without the event. I didn't type anything else in main.js... was there supposed to be something that notifies it what document this goes into?
Furthermore, in the HTML, I also tried to specify the type (although not necessary). It also didn't work.
I don't know if I made typos or anything... I suspect that it may be because I put them all in the same project file. The project file in sitting on my desktop. Could that be the cause of the problem?
EDIT
I have changed my main.js file to :
$(document).ready(() => {
$('.out').on('mouseover', ()=>{
$('.out').hide();
});
});
But it still doesn't work...
remove => from $(document).ready(function() => { and it will work (either it is in separate js file or added in HTML page itself)
Working snippet:-
$(document).ready(function(){
$('.out').on('mouseover', ()=>{
$('.out').hide();
});
});
<!DOCTYPE html>
<html lang="ru">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Language" content="ru">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!--used live jquery library to make it working -->
</head>
<body>
<div class="out"><p>Test</p>
</div>
</body>
</html>
Note:- You can do like this also
$(document).ready(()=>{
$('.out').on('mouseover', ()=>{
$('.out').hide();
});
});
Running Output:- https://jsfiddle.net/npthjwu1/
A bit more cleaner approach:-
$(document).ready(function(){
$('.out').on('mouseover',function(){
$('.out').hide();
});
});
remove => from $(document).ready(function()
I think the problem comes with the anonymous function syntax that you are passing in as jQuery event handlers. You are trying to use both the old school JavaScript lamba and the new ES lamba syntax.
Try removing the old school JavaScript anonymous function syntax function(){}, and use the new ES style () => {} (since it is the latest, which is supported by modern browsers) as follows...
$(document).ready(() => {
$('.out').on('mouseover', () => {
$('.out').hide();
});
});

Calling a javascript function in a document created with document.write

I have a web page with a button. The click code is:
var html = ...html string containing visual and script elements...
var view = window.open();
view.document.write(html);
view.init(<parameters>); // see next code block
the html content is:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="id1"></div>
<script>
function init(<parameters>) {
...work...
}
</script>
</body>
</html>
The problem is with the init function call in chrome: all good if I am in IE, but in chrome I get "init function not defined" exception.
How should I do to get this working in all browsers? Of course I am looking for a solution that doesn't require a server round trip.
IM a noob so idk if this is exaclty true but i have read that ie allows you to do alot more then chrome or firefox. It might be one of those example where ie will let you do something.
using document.write does in fact work when it comes to create the page I want. Problem is when I want to call a function defined in a javascript block inside that page. Different browsers give different results so I guess this is a matter not completely standardized yet. There are posts in the internet about this, but I couldn't find a clear and common answer.
I then solved my impasse with a workaround. The initial markup contains now placeholders for the parameters:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="id1"></div>
<script>
(init = function () {
var parameter1 = ${{placeholder1}}
var parameter2 = ${{placeholder2}}
...
...work...
})();
</script>
</body>
</html>
The creating code, then, replaces the placeholders with actual values:
var html = ...html string containing placeholders...
html = html.replace("${{placeholder1}}", actual1);
html = html.replace("${{placeholder2}}", actual2);
...
var view = window.open();
view.document.write(html);
Now the init function is called in the same page context, and this works in Chrome as well.
It is not possible to write to a new window if its not on the same domain. What I suggest is that you can open an iframe an work inside that.
How to write to iframe
How to write to page on same domain

how to load html page with javascript async calls using html-imports

im trying to load HTML page it has it is own data and ajax calls to render a view using html-import, but the issue is when the import happens the view yet not finish rendering, is there is a way to know when the view is finished calling and rendering all its element
(function(){
function createLauncherPanel() {
var div = document.createElement("div");
div.setAttribute("class", "launcher-panel");
div.classList.add("hidden");
div.appendChild(createLauncherLink(div));
document.getElementsByTagName("body")[0].appendChild(div);
return div;
}
function createLauncherLink(container) {
var link = document.createElement("link");
link.setAttribute("rel", "import");
link.setAttribute("href", "path-to-htmlpage-with-data-load -asynchronously-with-json-feed-and-view-to-render");
console.log('container',container);
link.addEventListener('load', function(e) {
// all imports loaded
console.log(e);
console.log('link',link);
console.log(link.import);
// #ele is the element i need to get from the imported page - but sence this element is not rendered yet because of the lateinse of rendering and network calls , this will return null
container.appendChild(link.import.querySelector('#ele'));
});
return link;
}
createLauncherPanel();
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.13/webcomponents-lite.js" type="text/javascript"></script>
</head>
<body>
<h1>Hello, worssld</h1>
<div id="ff"></div>
<script src="sc.js" type="text/javascript"></script>
</body>
</html>
I would suggest you to use the onload event as it will fire when everything has finished loading.
The onload event occurs when an object has been loaded.
onload is most often used within the element to execute a
script once a web page has completely loaded all content (including
images, script files, CSS files, etc.).

Adding an external JavaScript file in NetBeans and linking with the index file

I have added a JavaScript file into my existing project and referred that in the HTML file. The file structure is shown as its in the attachment. After I run the program, the output does not display what it is supposed to be.
Is there anything wrong with my file tree (how I am adding file into the project) or I am not referring the script the in the correct way?
Here is how my program looks like:
index:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="newjavascript.js" type="text/javascript"></script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
.JS:
document.getElementById("demo").innerHTML = 7+9;
It seems to be everything is ok with your project structure and refererring to js file inside index.html. However, the demo paragraph does not display what you want because it can be just not loaded in the time when your newjavascript.js is executed. I think you can try to modify it in the following way:
window.onload = function () {
document.getElementById("demo").innerHTML = 7+9;
};
Using onload function of window object you wait until a page (including demo paragraph) is loaded - and after it change its content.

How can I get the content of a loaded file (with script or link)

I was wondering, how I get the content of a loaded script, stylesheet, ... bye an accessing an id set on the element.
Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="../jquery-1.8.3.min.js"></script>
<script id="test" src="test.txt" type="text/isis-template"></script>
<!-- File contains "Hello world" -->
<script>
$(function () {
$('#test').GET_CONTENT_OF_LOADED_FILE
});
</script>
</head>
<body>
</body>
</html>
Background: I want to load HTML templates (e.g. for mustach, knockout), but don't want to write them into the page, I'd rather have them in a seperate file. Now I saw that I can load any file with the script or link tag, so I was testing if I can load them like this....
Any comments why this might be a bad idea or how it can be done better are appreciated.
Try using load()
$(function () {
$('#test').load('yourfolder/test.html', function(resp){
alert(resp);
});
});
If you have already load the contents in some html element
contents = $('#test').html();
So you want the content of text/isis-template file when document is ready?
You are lucky because this file doesn't fall for CORS but mine(the answer i was looking for and came here today) do.
Well just do ajax!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="../jquery-1.8.3.min.js"></script>
<!-- File contains "Hello world" -->
<script>
$(function () {
$.ajax({ url: "test.html"})
.done(function(cont) {
var GET_CONTENT_OF_LOADED_FILE=cont;
});
});
</script>
</head>
<body></body>
</html>
If you use debug tools and see the network activity, you will see that it does not load the external files (since it is not a text/javascript, and the browser does not know how to handle it)
(wrong test on my part, was testing local files)
So you only have a tag there with an id and an external resource in the src attribute. Treat it as just metadata.
You will have to manually load the resources
something like this
// load external template resources
$('script[type="text/isis-template"]').each(function(){
$(this).load(this.src);
});
For actual use you would need to make sure the templates are loaded before you try using them..

Categories

Resources