How to prefetch correctly a CSS file? - html

I use two CSS files, one is a little one for my home.html with all the important things for this page and there I pre fetch a bigger CSS file that takes care of the internal structure.
It works as I want but when I try to pass the W3C validation it complains with:
Error: A link element with an as attribute must have a rel attribute
that contains the value preload.
<link rel="prefetch alternate stylesheet" href="/css/internal.css" as="style">
Can I get rid correctly of this?

Related

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.

Include HTML into other HTML with web components

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

VB.Net - Properties in HTML attributes

I'm attempting to insert a base url property into some attributes for a .Net master page that I'm building.
The purpose of this attribute insertion is to make sure that I need only change a single value in a config file to change the head portion of a url, thus saving time when I'm moving my program between different servers.
On the code-behind of the master page I have an exposed property 'baseUrl' that stores the current base location path of the running program.
When I attempt to add my property into a script tag it looks like this:
<script type="text/javascript" src="<%# strBaseUrl %>/Javascript/Script.js"></script>
This will tend to work with the path changing based on a value I've set elsewhere in config.
However using the property in a similar way for CSS doesn't tend to work:
<link rel="stylesheet" href="<%# strBaseUrl %>/Style/StyleSheets/foundation.min.css">
Instead the string appended before the url doesn't reflect the contents of the 'strBaseUrl' variable and just appears as a set of periods and precentage symbols.
Does anyone know a correct means of concatenating the baseUrl into an HTML attribute for this purpose, that works with the link tag (i.e. CSS)?
This should work
<script type="text/javascript" src="<%=strBaseUrl%>/Javascript/Script.js"></script>

Difference between SRC and HREF

The SRC and HREF attributes are used to include some external entities like an image, a CSS file, a HTML file, any other web page or a JavaScript file.
Is there a clear differentiation between SRC and HREF? Where or when to use SRC or HREF? I think they can't be used interchangeably.
I'm giving below few examples where these attributes are used:
To refer a CSS file: href="cssfile.css" inside the link tag.
To refer a JS file: src="myscript.js" inside the script tag.
To refer an image file: src="mypic.jpg" inside an image tag.
To refer another webpage: href="http://www.webpage.com" inside an anchor tag.
NOTE: #John-Yin's answer is more appropriate considering the changes in the specs.
Yes. There is a differentiation between src and href and they can't be used interchangeably. We use src for replaced elements while href for establishing a relationship between the referencing document and an external resource.
href (Hypertext Reference) attribute specifies the location of a Web resource thus defining a link or relationship between the current element (in case of anchor a) or current document (in case of link) and the destination anchor or resource defined by this attribute. When we write:
<link href="style.css" rel="stylesheet" />
The browser understands that this resource is a stylesheet and the processing parsing of the page is not paused (rendering might be paused since the browser needs the style rules to paint and render the page). It is not similar to dumping the contents of the css file inside the style tag. (Hence it is advisable to use link rather than #import for attaching stylesheets to your html document.)
src (Source) attribute just embeds the resource in the current document at the location of the element's definition. For eg. When the browser finds
<script src="script.js"></script>
The loading and processing of the page is paused until this the browser fetches, compiles and executes the file. It is similar to dumping the contents of the js file inside the script tag. Similar is the case with img tag. It is an empty tag and the content, that should come inside it, is defined by the src attribute. The browser pauses the loading until it fetches and loads the image. [so is the case with iframe]
This is the reason why it is advisable to load all JavaScript files at the bottom (before the </body> tag)
update : Refer #John-Yin's answer for more info on how it is implemented as per HTML 5 specs.
apnerve's answer was correct before HTML 5 came out, now it's a little more complicated.
For example, the script element, according to the HTML 5 specification, has two global attributes which change how the src attribute functions: async and defer. These change how the script (embedded inline or imported from external file) should be executed.
This means there are three possible modes that can be selected using these attributes:
When the async attribute is present, then the script will be executed asynchronously, as soon as it is available.
When the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing.
When neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.
For details please see HTML 5 recommendation
I just wanted to update with a new answer for whoever occasionally visits this topic. Some of the answers should be checked and archived by stackoverflow and every one of us.
I think <src> adds some resources to the page and <href> is just for providing a link to a resource(without adding the resource itself to the page).
HREF: Is a REFerence to information for the current page ie css info for the page style or link to another page. Page Parsing is not stopped.
SRC: Is a reSOURCE to be added/loaded to the page as in images or javascript. Page Parsing may stop depending on the coded attribute. That is why it's better to add script just before the ending body tag so that page rendering is not held up.
Simple Definition
SRC : (Source). To specify the origin of (a communication); document:
HREF : (Hypertext Reference). A reference or link to another page, document...
SRC(Source) -- I want to load up this resource for myself.
For example:
Absolute URL with script element: <script src="http://googleapi.com/jquery/script.js"></script>
Relative URL with img element : <img src="mypic.jpg">
HREF(Hypertext REFerence) -- I want to refer to this resource for someone else.
For example:
Absolute URL with anchor element: Click here
Relative URL with link element: <link href="mystylesheet.css" type="text/css">
Courtesy
A simple definition
SRC: If a resource can be placed inside the body tag (for image, script, iframe, frame)
HREF: If a resource cannot be placed inside the body tag and can only be linked (for html, css)
You should remember when to use everyone and that is it
the href is used with links
<link rel="stylesheet" href="style.css" />
the src is used with scripts and images
<img src="the_image_link" />
<script type="text/javascript" src="" />
the url is used generally in CSS to include something, for exemple to add a background image
selector { background-image: url('the_image_link'); }
after going through the HTML 5.1 ducumentation (1 November 2016):
part 4 (The elements of HTML)
chapter 2 (Document metadata)
section 4 (The link element) states that:
The destination of the link(s) is given by the href attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If the href attribute is absent, then the element does not define a link.
does not contain the src attribute ...
witch is logical because it is a link .
chapter 12 (Scripting)
section 1 (The script element) states that:
Classic scripts may either be embedded inline or may be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.
it doesn't even mention the href attribute ...
this indicates that while using script tags always use the src attribute !!!
chapter 7 (Embedded content)
section 5 (The img element)
The image given by the src and srcset attributes, and any previous sibling source element's srcset attributes if the parent is a picture element, is the embedded content.
also doesn't mention the href attribute ...
this indicates that when using img tags the src attribute should be used aswell ...
Reference link to the W3C Recommendation
If you're talking HTML4, its list of attributes might help you with the subtleties. They're not interchangeable.
They are not interchangeable - each is defined on different elements, as can be seen here.
They do indeed have similar meanings, so this is an inconsistency. I would assume mostly due to the different tags being implemented by different vendors to begin with, then subsumed into the spec as is to avoid breaking backwards compatibility.
They don't have similar meanings. 'src' indicates a resource the browser should fetch as part of the current page. HREF indicatea a resource to be fetched if the user requests it.
From W3:
When the A element's href attribute is
set, the element defines a source
anchor for a link that may be
activated by the user to retrieve a
Web resource. The source anchor is the
location of the A instance and the
destination anchor is the Web
resource.
Source: http://www.w3.org/TR/html401/struct/links.html
This attribute specifies the location
of the image resource. Examples of
widely recognized image formats
include GIF, JPEG, and PNG.
Source: http://www.w3.org/TR/REC-html40/struct/objects.html
I agree what apnerve says on the distinction. But in case of css it looks odd. As css also gets downloaded to client by browser. It is not like anchor tag which points to any specific resource. So using href there seems odd to me. Even if its not loaded with the page still without that page cannot look complete and so its not just relationship but like resource which in turn refers to many other resource like images.
src is to used to add that resource to the page, whereas href is used to link to a particular resource from that page.
When you use in your webpage, the browser sees that its a style sheet and hence continues with the page rendering as the style sheet is downloaded in parellel.
When you use in your webpage, it tells the browser to insert the resource at the location. So now the browser has to fetch the js file and then loads it. Until the browser finishes the loading process, the page rendering process is halted. That is the reason why YUI recommends to load your JS files at the very bottom of your web page.

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" />