Where should I put tags in HTML markup?

[Origin]: https://stackoverflow.com/questions/436411/where-should-i-put-script-tags-in-html-markup

When embedding JavaScript in an HTML document, where is the proper place to put the tags and included JavaScript? I seem to recall that you are not supposed to place these in the  section, but placing at the beginning of the  section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the  section as a logical place for  tags.

So, where is the right place to put the  tags?

(This question references this question, in which it was suggested that JavaScript function calls should be moved from  tags to  tags. I’m specifically using jQuery, but more general answers are also appropriate.)

shareedit

Here’s what happens when a browser loads a website with a  tag on it:

  1. Fetch the HTML page (e.g. index.html)
  2. Begin parsing the HTML
  3. The parser encounters a  tag referencing an external script file.
  4. The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
  5. After some time the script is downloaded and subsequently executed.
  6. The parser continues parsing the rest of the HTML document.

Step 4 causes a bad user experience. Your website basically stops loading until you’ve downloaded all scripts. If there’s one thing that users hate it’s waiting for a website to load.

Why does this even happen?

Any script can insert its own HTML via document.write() or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded & executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.

However, most javascript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:

<!-- index.html -->
<html>
    <head>
        <title>My Page</title>
        <script type="text/javascript" src="my-script.js"></script>
    </head>
    <body>
        <div id="user-greeting">Welcome back, user</div>
    </body>
</html>

Javascript:

// my-script.js
document.addEventListener("DOMContentLoaded", function() { 
    // this function runs when the DOM is ready, i.e. when the document has been parsed
    document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});

Because your browser does not know my-script.js isn’t going to modify the document until it has been downloaded & executed, the parser stops parsing.

Antiquated recommendation

The old approach to solving this problem was to put  tags at the bottom of your , because this ensures the parser isn’t blocked until the very end.

This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts & stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn’t load within 2 seconds, people will go to another website.

In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.

The modern approach

Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it’s safe to continue parsing while the scripts are being downloaded.

async

<script type="text/javascript" src="path/to/script1.js" async>
<script type="text/javascript" src="path/to/script2.js" async>

Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it’s downloaded, without blocking the browser in the meantime.
This implies that it’s possible to script 2 is downloaded & executed before script 1.

According to http://caniuse.com/#feat=script-async, 90% of all browsers support this.

defer

<script type="text/javascript" src="path/to/script1.js" defer>
<script type="text/javascript" src="path/to/script2.js" defer>

Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.

Unlike async scripts, defer scripts are only executed after the entire document has been loaded.

According to http://caniuse.com/#feat=script-defer, 90% of all browsers support this. 92% support it at least partially.

An important note on browser compatibility: in some circumstances IE <= 9 may execute deferred scripts out of order. If you need to support those browsers, please read this first!

Conclusion

The current state-of-the-art is to put scripts in the <head> tag and use the async or deferattributes. This allows your scripts to be downloaded asap without blocking your browser.

The good thing is that your website should still load correctly on the 20% of browsers that do not support these attributes while speeding up the other 80%.

P.S. See also Google’s explanation: https://developers.google.com/speed/docs/insights/BlockingJS

shareedit

 

Advertisements

How do I force a favicon refresh

[Origin]: https://stackoverflow.com/questions/2208933/how-do-i-force-a-favicon-refresh

To refresh your site’s favicon you can force browsers to download a new version using the link tag and a querystring on your filename. This is especially helpful in production environments to make sure your users get the update.

<link rel="icon" href="http://www.yoursite.com/favicon.ico?v=2" />
shareedit

separate files (HTML5,CSS & JS)

Origin: https://stackoverflow.com/questions/12151708/separate-files-html5-css-js

Just declare references to your CSS & JS from within your HTML. For performance reasons, it’s good to put the CSS reference in the head, and the JS reference at the end of the file just before closing out the tag. That way, your page will load and will look correct right off the bat and won’t be blocked downloading the JavaScript. The JS will be the last thing to load. Here’s an example of the HTML markup:

<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyles.css" />
</head>

<body>
...

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="myscript.js"></script>

</body>
</html>
share

The default character set of URLs when used in HTML pages and in HTTP headers is called ISO-8859-1 or ISO Latin-1.

http://stackoverflow.com/questions/696659/why-is-this-appearing-in-my-c-sharp-strings-%C3%82%C2%A3

The default character set of URLs when used in HTML pages and in HTTP headers is called ISO-8859-1 or ISO Latin-1.

It’s not the same as UTF-8, and it’s not the same as ASCII, but it does fit into one-byte-per-character. The range 0 to 127 is a lot like ASCII, and the whole range 0 to 255 is the same as the range 0000-00FF of Unicode.

So you can generate it from a C# string by casting each character to a byte, or you can use Encoding.GetEncoding("iso-8859-1") to get an object to do the conversion for you.

(In this character set, the UK pound symbol is 163.)

Background

The RFC says that unencoded text must be limited to the traditional 7-bit US ASCII range, and anything else (plus the special URL delimiter characters) must be encoded. But it leaves open the question of what character set to use for the upper half of the 8-bit range, making it dependent on the context in which the URL appears.

And that context is defined by two other standards, HTTP and HTML, which do specify the default character set, and which together create a practically irresistable force on implementers to assume that the address bar contains percent-encodings that refer to ISO-8859-1.

ISO-8859-1 is the character set of text-based content sent via HTTP except where otherwise specified. So by the time a URL string appears in the HTTP GET header, it ought to be in ISO-8859-1.

The other factor is that HTML also uses ISO-8859-1 as its default, and URLs typically originate as links in HTML pages. So when you craft a simple minimal HTML page in Notepad, the URLs you type into that file are in ISO-8859-1.

It’s sometimes described as “hole” in the standards, but it’s not really; it’s just that HTML/HTTP fill in the blank left by the RFC for URLs.

Hence, for example, the advice on this page:

URL encoding of a character consists of a “%” symbol, followed by the two-digit hexadecimal representation (case-insensitive) of the ISO-Latin code point for the character.

(ISO-Latin is another name for IS-8859-1).

So much for the theory. Paste this into notepad, save it as an .html file, and open it in a few browsers. Click the link and Google should search for UK pound.

<HTML>
  <BODY>
    <A href="http://www.google.com/search?q=%a3">Test</A>
  </BODY>
</HTML>

It works in IE, Firefox, Apple Safari, Google Chrome – I don’t have any others available right now.

shareedit

HTML Button Close Window

http://stackoverflow.com/questions/8057802/html-button-close-window

When in the onclick attribute you do not need to specify is javascript.

<button type="button" onclick="window.open('', '_self', ''); window.close();">Discard/<button>

This should do it. In order to close it your page need to be opened by the script, hence the window.open. Here is an article explaining this in detail: http://www.yournewdesigner.com/css-experiments/javascript-window-close-firefox.html

shareedit

How do I make a div hidden by default using javascript?

http://stackoverflow.com/questions/19163327/how-do-i-make-a-div-hidden-by-default-using-javascript

In cases such as this I hide the div using css, either inline or in the stylesheet, so that it is hidden by default.

<div style="display:none;"> 

Or, you could load the div without content, then populate it via your javascript with e.innerHTML=”some content” or ajax?

shareedit