which was first execute in HTML file head or body? - javascript

In HTML which was execute first head tag or body tag. I had this doubt while learing javascript and i need to include this file to the html so that.

It goes from top to bottom so the head executes first then the body, you can try it your self:
<head>
<title>test</title>
<script> alert('From Head'); </script>
</head>
<body>
<script>alert("From Body");</script>
</body>
Here is a codepen

It goes from top down, calling each script it finds while parsing the whole HTML document (normally the head tag goes first, with all the scripts inside, in the order they were placed). So if you need to include JS files, always put the least dependant ones at the top.
Also, if your JS scripts access DOM elements, make sure the script runs after the DOM is ready, by either using a window onload callback or placing the script before closing the body tag (so it comes "after" the DOM stuff).

Related

In what case can script tags in HTML markups be included in the head tags without using async and defer attributes?

Hi guys I’m new to JavaScript and web development. I came across this question recently about the location of the script tag. I know it’s a common question and I’ve viewed some answers on stackoverflow also this style guide on google. but I am still not very clear on this problems.
For example, I have I html page with an external script js file like this
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src='js.js'>
</script>
</head>
<body>
</body>
</html>
and the js file is
var loadTime = document.createElement('div');
loadTime.textContent = 'You loaded this page on: ' + new Date();
loadTime.style.color = 'blue';
document.body.appendChild(loadTime);
It seems to me that this js file is not dependent upon any DOM elements of the html file being available so it should not matter where I put this script tag. But it turns out I have to put this script tag to the bottom of the body closing tag, otherwise the date won't appear on the page as expected. Another workaround is using defer attribute in the script tag like this
<script src='js.js' defer></script>
This is what baffles me, if a script has any operation related to DOM, it seems to me that it cannot be put at inside the head tag at the front without a defer or async attribute in it. Why this google style guide https://developers.google.com/speed/docs/insights/BlockingJS still suggest we can write inline script in the head tag given accessing and operating on DOM are incredibly common in any script file.
According to http://caniuse.com/#feat=script-defer, 94.59% of all browsers support this. 94.92% support it at least partially. Why the async and defer attributes are not used widely? I mean, I viewed a lot of HTML sources out there, and I just don't see the async and defer attributes anywhere?
So here are some explenations.
Using <script></script> in HTML without any extra attributes will block HTML parsing (in other words 'loading html to browser window') from that point. Specified script will be then fetched and executed upon successful download. After that, execution will be resumed (page will be loaded).
Using <script async></script> allow HTML parser not to block parsing until the script is downloaded.
Using <script defer></script> allow HTML to be fully parsed, and script code will be executed after that.
So to anwser your question from the topic - scripts in <head></head> can be included (and will work properly) if they do not require to acces things that are not there yet.
In your example you are trying to append sth to body (which is not yet there).
If you are using <script async></script> in <head></head> it is also not guaranteed to work. Eg. script is tiny (almost instant download) - it will be executed before html is fully parsed (results in accessing things that are not there yet). We can time async requests, it's part of their beauty.
Using async makes sense if fetched script is not accesing DOM straightforward.
Using defer makes sense eg. if JS file is big (eg. fetch takes 5sec) and we want to show user sth. on the page. After script is loaded we change the page to it's inteded 'look' via js in script.
Note that these are not all use cases of async and defer.
Suggest you check the answer of this load and execute order of scripts
The normal way is in the head tag only loading the javascript.
Then after the whole html file is loaded, in the document onload call your functions.
document.addEventListener('DOMContentLoaded', function() {
console.log('document - loaded - ');
//call your functions
}, true);

Is window.addEventListener("load",function() faster than <script> placed on bottom of page?

I have a simple Javascript function that can be placed anywhere within HTML document. So I put it right below the closing , for example:
<html>
<body>
Some text.
<script>
document.getElementsByTagName('body')[0].innerHTML='hello';
</script>
</body>
</html>
My question is - would it make sense (from page load speed point of view) to load this script via the addEventListener("load") function instead? Ie. if I use this code below - which would be preferred? I understand that when Javascript is on the bottom of the page, it won't 'block' page rendering anyway, so using the addEventListener may only slow the execution down?
<html>
<body>
Some text.
<script>
window.addEventListener("load",function()
{document.getElementsByTagName('body')[0].innerHTML='hello';},
false);
</script>
</body>
</html>
Scripts should generally not be placed directly in the HTML like that, because they block further HTML parsing until they're executed. While it's not a problem if you have only one script, what if you have two, or three, or more, and some of them might take more than a handful of ms to parse?
Still, assuming that blocking isn't an issue, there's no real difference on way or the other, from the UX point of view.
Scripts, being information about how to interact with the content, but aren't actually content themselves, belong in the <head> IMO. If you don't like wrapping everything in a load listener, you can use the defer attribute to automatically run the script once the whole HTML has been parsed: <script src="..." defer>.

Preloader code - where to put it in the html document

This is the code for my preloader:
$(window).load(function() {
$(".preloader").fadeOut("slow");;
});
My question is, where in the html document I should put the code. I've seen it done various different ways on different example websites. Some put the code inside script tags just after the <head> tag (before they declare their css), others put it inside script tags after importing css/other scripts so just above the closing </head> tag. Others put it inside a script tag just before the </body> closing tag.
I'm sort of confused because the whole point of a preloader is to wait for the content to be loaded so should it not go right at the top, before css and other script imports inside the <head> tag?
Thanks.
Best practice is to put all scripts at bottom of body for page rendering performance purposes
However since you are using a load event it doesn't matter. The code inside the load handler won't run until the window is loaded, regardless of where you place it in the page.
That event won't trigger until all the resources that exist in the html source are loaded ... css, scripts, images etc. It does not however know about any ajax or other asynchronous content you may be adding
note however that $(window).load() is deprecated and you should use
$(window).on('load', function() {
$(".preloader").fadeOut("slow");
});
And if you aren't worried about images can use
$(function() {
$(".preloader").fadeOut("slow");
});

Where exactly should I attach script in HTML?

I have read about several ways to embed Javascript in HTML document.
First, in head section:
<head>
...
<script src="abc.js"></script>
</head>
Second, in the end of document's body:
<body>
<!-- content -->
<script src="abc.js"></script>
</body>
First way is more esthetic, but second version assures that all the items in DOM are loaded. I use HTML5 (but probably it doesn't matter)
Which way is better and why?
if it is just a library of functions which aren't suppose to run when the page loads, you can safely put it in the head. Otherwise you need to wrap the code in abc.js with window.onload or $(document).ready(); and then embed it in the head
It depends on when you need the functionality in the script.
Before page load or else.
If it doesn't matter the second one in your example is better and more seciure since it allows the page content to load.
An error in the script may prevent for this to happen in before body case.
A lot depends on when you need script to execute if you need the page to be fully loaded or not. You can possibly put it in the head then execute a function with the onload event.

why does jquery's .load() ignore <script>?

I have a every common page a.html which looks like this:
<html>
<head>
<script type="text/javascript" src="xyz.js" > </script>
</head>
<body>
<div> ... </div>
</body>
</html>
In b.html, I use jquery's .load() function to a div.
$("#myDiv").load("a.html")
It works. The xyz.js's content is loaded along with a.html. But why isn't there a <script> tag? I open firebug to see the source. There is a's but no a's <script>.
I want the <script> because I need it to find relative path.
(this question)
Edit: I tried to use .get() and .html(). Didn't help.
Edit2: The title is not very appropriate. The xyz.js runs. But no <script>.
The .load() function purposefully strips out <script> tags from the loaded content. When you give it a plain URL to load, it will execute the scripts after loading the content and adding it to the DOM. However, if you use the trick of adding a selector after the URL in the first argument:
$('#foo').load("http://some.domain.com/blah #special-div");
then it strips the <script> tags but it does not execute them.
Why? I don't know.
Now, please note that loading an entire page from the <html> tag on down into an element of another page is going to result in some sort of Frankenstein monster of a DOM, if a browser will do it at all. Generally, when you use ".load()" to grab fragments of content to update a page, your server should respond with a piece of a page, not the whole thing. The jQuery deal with allowing a selector after the actual URL is intended to let you strip out a chunk of a page, which is really cool, but it has that drawback that the scripts won't be executed in that case.
Because, it cannot run the script inside the <SCRIPT> tag. jQuery has .getScript() to call for scripts only. Check here

Categories