Include HTML into other HTML with web components - html

What is the right way to insert HTML snippet into main HTML file with HTML5 imports?
The answer to more generic question https://stackoverflow.com/a/22142111/239247 mentions that it is possible to do:
<head>
<link rel="import" href="header.html">
</head>
But this doesn't work. I don't need to insert JS and CSS. Only plain HTML markup inserted at the top of <body>. What is the most simple way to do this and keep HTML readable?

The way I have found to do this is to use ASP.NET and .cshtml files and use razor, as seen here:
http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts
Beyond simply inserting html into other html this also allows you to have consistent navigation bars, footers, etc. and minimizes your code profile. Also, the use of a layout file gives the site a better feel as only a section of the site refreshes when you click an internal link, as opposed to the whole site.

Found a way to do this from html5rocks, but it is far from being readable. This is the ideal way:
<body>
<include src="header.html"/>
</body>
And this is how it is implemented by HTML5 imports:
<head>
<link rel="import" href="header.html">
</head>
<body>
...
<script>
document.body.appendChild(
document.querySelector('link[rel="import"]')
.import
.querySelector('body')
.cloneNode(true));
</script>
</body>
Notes:
not clear how to choose include if both header.html and footer.html are there
querySelector('body') is required to avoid Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node': Nodes of type '#document' may not be inserted inside nodes of type 'BODY'.
not clear how to insert <body> tag contents without the tag itself
HTML5 import doesn't work in Firefox (38) http://caniuse.com/#feat=imports =/

See: http://www.w3schools.com/angular/angular_includes.asp
It says:
HTML Includes in Future HTML. Including a portion of HTML in HTML is, unfortunately, not (yet) supported by HTML.
So this is on its way, but not here yet.
EDIT: If you are able to, I would use PHP, which is close to the level of cleanliness. The link I inclueded shows multiple ways to do what you are trying to do.
Late edit: if it still counts (for those worried about sourcing): http://caniuse.com/#feat=imports

Related

Why does linking libraries from thymyleaf fragments need double linking?

I have a question about linking libraries.
I usually do it this way:
<link href="sidebar/common/style.css" rel="stylesheet">
but now I wanted to start using thymeleaf fragments. Each tutorial I've seen about linking libraries using thymeleaf fragments looks the same. Why people always put "double" linking if it isn't necessery? (my code above works well and i don't need to link this libraries second time using thymeleaf)
For example my code above in every tutorial will look:
<link href="sidebar/common/style.css"
th:href="#{sidebar/common/style.css}" rel="stylesheet" >
Can anyone explain what is the correct and recommended way to link these libraries?
What about javascript and fontawesome linking?
I am sorry for this kind of question but I am just starting with thymeleaf and it gives me no peace. I hope that this will not upset the admin and a good answer will also be useful to others
There is no need to use both of the linking types simultaneously, unless you really need it for example for quick prototyping.
href="sidebar/common/style.css" is being used only when you open your template directly in the browser. It is a standard HTML tag which will be processed by your browser, while th:href will be ignored.
Whereas th:href="#{sidebar/common/style.css} will be processed by the template engine and href will be substituted by Thymeleaf.
Similarly, Thymeleaf will override the content of any HTML tag, then there is a th:text attribute present, for example:
<p th:text="${variableName}">That text will be overriden by variableName value</p>

Is three any way to use a require() like function inside an HTML file to render a nested HTML file?

I'm trying to use an HTML template as a frame, and want to load the content inside of it depending on the route.
I'm used to PHP, so I know the require($file) option embeded in the code so it will render the needed file inside of the template, so I'd like to know if there is any thing similar to it.
I've tried to search about it, but it isn't that clear. So I've thought in two options, the first one is to split the template in two parts, and put the file content in between these two when sending the response.
This is what I am aiming for in the main HTML file and be able to render it in the NodeJS response.
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>My App</h1>
{ require($file); }
</body>
</html>
Easy way is to read the template (with some placeholders for the variable text) into a variable. Then read the text that you want to put into the placeholders into another variable. Then just replace the placeholders. Output the final string.
You can use https://www.npmjs.com/package/mustache to render templates in node - it includes partial HTML templates and should feel familiar to your PHP experience.
(Just to answer you question directly - no, HTML by itself is static, and with exception of iframe, there is no safe way to include partial HTML within another HTML page.)
you can use the iframe HTML object to embed it inside your file
<iframe src="<source html file location>"></iframe>
No. There's no way to add a 'variable' in HTML since HTMl it static. You need a dynamic language for that such as:
mustache.js
handlebars.js
pug/jade
Or if you're feeling really passionate about web development, and you are willing to begin hating html, then you should defiantly check out:
react.js Personal Favorite
angular
Let me know if you have any questions!!

Understanding Render Blocking CSS

I am trying to understand how CSS is evaluated in a specific setting:
Lets assume I have the following content in my <head> tag:
<html><head>
...
<link href="reset.css" type="text/css" rel="stylesheet">
<link href="style.css" type="text/css" rel="stylesheet">
<link href="autocomplete.css" type="text/css" rel="stylesheet">
</head>
<body>
... html ...
<script type="text/javascript" src="/js/script.js"></script>
</body></html>
Now, let's assume reset.css and style.css contain some rules that immediately affect the above the fold content or the the elements in the HTML. However, autocomplete.css only contains class used that are used later by some JavaScript.
Now, let's further assume the browser already downloaded reset.css and style.css but autocomplete.css is still pending.
I am wondering what would happen if the browser would do it encounters the blocking script tag at the end of the page? Obviously, it can render the HTML up to the script tag, but is the execution of the script blocked by the missing autocomplete.css?
Note that the script tag is not a sync.
I've read:
https://developers.google.com/web/fundamentals/performance/critical-rendering-path/analyzing-crp
And there it says that the execution of the JavaScript is blocked until the CSSOM is there.
Now:
1. Will the page start rendering even autocomplete.css has not yet arrived? and,
2. Is the execution of the script.js javascript blocked until the autocomplete.css is there?
Note, I am referring to two different things: rendering and script execution.
All CSS is render blocking. The only exception from this rule would be CSS that your DOM does not yet know about (loaded async, built/loaded on the fly via javascript).
Until your browser didn't resolve (or thinks it resolved) all CSS by building the CSS Object Model, the page won't render and javascript will not be executed. However, resolve does not necessarily mean load. It can mean two things:
load & parse. If it's above 2k lines of code, you're going to notice it when measuring with proper tools. If it's above 10k lines of code, you'll be able to notice it without using any tools. This is regardless if it contains rules concerning elements above the fold or not.
not being able to load/parse (due to network problems or invalid rules) - if an error is returned when CSS is loaded/parsed, it will resolve faster and the resulting differences will be hardly noticeable. If the server does not return an error (and just doesn't respond) - that's going to block your CSSOM from building, your page from loading and your scripts from executing.
Resources:
W3C's CSSOM spec.
MDN's CSSOM resource page
What is CSSOM?
The latest performance recommendations are as follows:
1) Inline all css into the header that the browser needs to render above-the-fold-content. Content which is visible without scrolling.
2) Add all other css to the bottom of the page or better load it asynchronously with something like this: https://github.com/filamentgroup/loadCSS
autocomplete is a css file. As such, it only adds style properties to the classes which are defined in the html. The javascript will still execute correctly, even if the css is missing.
The only thing that might happen is that if the js changes some css styles of the classes which style is defined in autocomplete.css. However even then it's unlikely.

common element in html

I am developing a project and find that there are elements that are common to all pages, I wonder if there is any way to define these elements generally and call them from your html to avoid having to define each of the pages. thank you very much for your help
test.html
<div>Menu</div>
When you need to have this menu, just call this code in your page:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
load()
Another option could be AngularJS, or just something like includes with PHP.
I don't know any way to do exactly this with pure HTML, but by mixing in a little server side script, you can. Just to give you an idea what it would look like:
This example uses PHP. If you are on a Microsoft server, you would need to translate this example into .NET or .aspx.
First, save the following to a file called "mytest.php" in the same folder as your other pages. (You can put it in a subfolder if you wish, but for this example I will keep it simple).
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Just one line for this test. A little useless, but you can see the point.
Now, in the <head> tag of your HTML, you can do this (I added the <head> tags just so you can see it... You would not want to have TWO sets of <head> tags.)
<head>
<?php include 'mytest.php'; ?>
</head>
Now, visit the page and display the HTML and you should see that line incorporated into your HTML. Note that any document that contains PHP code (as above) must end with a .php extension.
As #loops suggested, I would highly recommend AngularJS for the rescue.
It's a great MVC framework built with JavaScript and no external dependencies.
It offers the possibility to create custom elements using their Directives
So you could create a new element <mymenu></mymenu> and you can give this new tag some behaviour as well as bind events to it.
AngularJS takes care of all the rest and your new tag will be available across all the pages of your application.
And yes, you are correct thinking that should be done on the client side rather than server side.
I am happy to provide a full working example for you once you get your head around the framework first. Otherwise I think it will be too much information at once ;)

Can I load javascript code using <link> tag?

Can I load javascript code using <link> tag in my website ?
For example I have a javascript file, test.js, which contains the simple code alert('hello');
Can I make the popup window appear using:
<link href="test.js"></link>
No. There was a proposal to allow:
<link rel="script" href=".../script.js"/>
analogously to stylesheets. This is even quoted as an example in the HTML 4 DTD, but browser implementation never happened. Shame, as this would have been much cleaner.
You need to use the <script> tag to include JavaScript source files:
<script type="text/javascript" src="mysrc.js"></script>
The end tag must be the full </script>, don't abbreviate the way you can with some tags as in <script type="text/javascript" src="..."/>.
Yes, alert statements in the included source will appear when they are evaluated by the browser.
For information on the uses of the <link> tag, see w3.org.
Modern browsers support the preload keyword, which is used to preload various resources, including scripts. From MDN:
The preload value of the <link> element's rel attribute allows you to
write declarative fetch requests in your HTML <head>, specifying
resources that your pages will need very soon after loading, which you
therefore want to start preloading early in the lifecycle of a page
load, before the browser's main rendering machinery kicks in. This
ensures that they are made available earlier and are less likely to
block the page's first render, leading to performance improvements.
A simple example might look like this (see our JS and CSS example
source, and also live):
<head>
<meta charset="utf-8">
<title>JS and CSS preload example</title>
<link rel="preload" href="style.css" as="style">
<link rel="preload" href="main.js" as="script">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>bouncing balls</h1>
<canvas></canvas>
<script src="main.js"></script>
</body>
Possible rationale why not
link elements are only allowed where "Metadata content" is allowed, typically head, and not in the body. See: Contexts in which this element can be used. All embedded elements that go in the body have separate elements for them: img, iframe, etc.
link elements must be empty, and script may be non-empty. See: Content model
Therefore it is natural to have a separate element for JavaScript, and since we must have a separate element, it is better not to duplicate functionality with link rel="script".
This theory also explains why img and style have separate elements:
img can be placed in the body, so it gets a separate element, even though it must be empty.
style can be non-empty, so it gets a separate element, even though until HTML5 it could not be placed in the body (now it can via scoped, but still not to include external scripts).
Apparently Tim Berners-Lee wanted everything to be done with <a: https://youtu.be/3QEoJRjxnxQ?t=901 !
JavaScript code would generally be loaded using a script tag, like so:
<script type="text/javascript" src="test.js"></script>
To answer your question directly, no. Not by that method. However I was led to this question while searching a similar issue which lead me to this question. Seeing the answers already supplied which for the most part are correct I went to check syntax on http://w3schools.com/ . It seems that with HTML5 there is a new attribute for for the script elements in html.
This new attribute allows javascript files to be defered or loaded and executed asynchronously (not to be confused with AJAX).
I'm just going to leave the link here and let you read up on the details yourself as it is already supplied on the internet.
http://www.w3schools.com/tags/att_script_async.asp
The other option for this is, you can dynamically insert a script file into the current document, by creating a SCRIPT tag, setting its "src" attribute to the URI of the script, and then inserting it as a child of the page's HEAD node.
Doing those things will get the browser to fetch the script file, load it into the document, and execute it.
Typically you would use a <script> tag, but actually, you can do <link href="test.js"></link> as you described. Here is a example
I'm wrong here. Apparently, Parcel is doing some special stuff and the final output uses a <script> tag. You need a script tag (even if you use <link> to preload a .js file, you still are forced to use a <script> tag to actually load it).
Leaving this here so that others might not be confused by Parcel's bundling magic as I was.
No. A Link tag like is for CSS files or for relational links (like next).
This is not the way to load javascript into the page. You need to use the <script> tag:
<script language="javascript" src="file.js" />