Where is the ideal place to load javascripts in html? [duplicate] - javascript

This question already has answers here:
Where should I put <script> tags in HTML markup?
(21 answers)
Closed 2 years ago.
I understand inline javascripts scattered through html code like the following example is bad
<html>
<head>
</head>
<body>
<p> Foo <script></script></p>
</body>
</html>
However, after coding for a while, understanding that loading Javascripts at the end of the document is the best way to go. I do see a lot of the sites that conform to loading scripts at the end of their document, do so in the following manner :
<html>
<head>
</head>
<body>
<p> Foo </p>
<script></script>
</body>
</html>
What is not made clear, is why not :
<html>
<head>
</head>
<body>
<p> Foo </p>
</body>
<script></script>
</html>
.. as this is outside the body tag which means that the body (in theory) can process faster and still load your scripts before finalizing on </html>.
Or even this :
<html>
<head>
</head>
<body>
<p> Foo </p>
</body>
</html>
<script></script>
Each variation will have (in theory) different performance results, and/or may break functionality in the page depending on the script contents of course.
Of the above formats, which one is the ideal place to load javascripts that would have the highest performance gain without breaking html ?

The best place at the end of the body tag, like
<html>
<head>
</head>
<body>
some html body tags
.
.
.
<script> external or inline </script>
</body>
</html>
If you do like so, then the html will load quicker and main pros is that all your ids and classes will get assigned otherwise sometime if you put script above html, then there might be a chance that you try to get an element by id that is not yet assigned in DOM
[UPDATE]
Here is an example code that Bootstrap is using in their own website: http://getbootstrap.com/getting-started/
you can find this code under Basic template Heading:
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

As noted here, the script tag won't validate outside of the body or head tags. However, you want to place it as far down as possible, so that the rest of the page loads first, to avoid errors. This leaves us with the place furthest down, but inside the body and head tags: just before the closing body tag.
<html>
<head>
</head>
<body>
<p> Foo </p>
<script></script>
</body>
</html>

If you know how the browsers work it will be easy to know where to put it.
First of all it's invalid to include your script after the body or the html element. Only comments and the closing tag for html are allowed after the body. Some browser will do recovery but you shouldn't depend on that.
You may include it any where in the body or the head but you should know that script take the browser attention may be for while and I will stop rendering the dom. That's very bad for user experience so the best place to include it just at the end of the body element.
Like in the example :
<html>
<head>
</head>
<body>
<p> Foo </p>
<!-- ... -->
<script></script>
</body>
</html>
One more thing if you include the script at the top of the page and that script will manipulate the dom that may cause an error if the dom isn't ready yet. The script searching for element which is not exist yet. And it will be very confusing when it runs at time and it doesn't run in another time. You may check the answers for similar questions here and here

How browsers work: As you can see from here, most of the browsers parsing the html elements top to bottom in elements tree hieararchy.
So, when you put a script just before </body> tag, make sures that most of the elements has been loaded or at least parsed. Or, you just need to wait for document.readyState.
Also, by putting your script below </body> tag is semantically not good. But, you can do it and it won't make a difference for the performance.

Important thing to note is the following:
If you put the script in the head tag HTML page rendering is blocked until the script is downloaded.
The more scripts you will put there the slower your page will load.
That’s why an advanced approach is to put the scripts at the bottom of the BODY, and in this case the user can start interacting with a page before the Javascript has Loaded.
You will put the scripts in HEAD only if they MUST be available before the page is shown.

Best way to load your java-script at the end of body tag, but in some case when you use third party script, it need be load before control initialize.
<html>
<head>
</head>
<body>
...........
<script></script>
</body>
</html>

JavaScript is a render blocking resource. So when browser is parsing HTML document and encounters script in between, the control is passed to js engine. Which runs the script and returns the control to browser again.
<html>
<head>
<script src="/main.js" />
</head>
<body>
<script>
//some inline script
</script>
</body>
</html>
So when broswer encounters the script tag in header, it passes the control to js engine. Now beacuse the script is being loaded from network, js engine will wait for script to load. After that it will be executed. Then document parsing will resume. (Inline script in head would have worked faster as network delay would be avoided)
Same goes for inline script. Situation gets complex if CSS is also present along with javascript. If a CSS is also being loaded from network in the head, js engines will wait for it too. So there are 2 dependencies now.
So it is best to add js at the bottom and CSS at top generally (to avoid Flash of Unstyled Content).
A good read for the same is present here :
Critical Rendering Path

Related

Html external script not working

I have create a external script call script.js save in js folder. However i don't know why it is not working. Therefore, I have tried put the into the html file and it work fine. So I think it is the problem of missing something in or i don't know.
It is my html code
<!DOCTYPE html>
<html>
<head>
<title>...........</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
<script src="js/script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<button class="button">show</button>
<p>yo</p>
</body>
JQuery
$(".button").click(function(){
$("p").toggle();
});
Ensure jquery is loaded first:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/script.js"></script>
I'd also move this to just before the closing </body> tag in your HTML.
And then check where the JS folder is relative to the HTML file you've written. Currently, the folder would need to be at the same level in the directory structure as the HTML file.
Inside your script, use window.onload. The script might be firing before the DOM has actually finished loading.
You might also want to put jQuery on top so that it finishes loading before any possible jQuery code in your script fires.
Try loading JS in the footer.
You need the elements to be present in DOM before you can select them.
Moreover including external js files at the bottom of your page, gives priority of your HTTP requests to the visual display that will be presented to the client instead of to the logic of interaction or dynamics;
this is the usual behavior you'd want.
If you are using jquery in your JavaScript code please put them in this order
<!DOCTYPE html>
<html>
<head>
<title>...........</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/script.js"></script>
</head>
If that is not the case can you post the error in the console (using chrome press f12 to see the errors in the console)
Other thing you can check, the js folder is in same directory where your html page is?
let us know

Remove Render Blocking Javascript

I tried Google PageSpeed Insights to check how much my website speed does well! But it shows an error in mobile version. Google suggested me to remove render blocking javascript to make my site better looks in mobile device. I've written bellow what exactly they said to me.
Your page has 1 blocking script resources and 3 blocking CSS
resources. This causes a delay in rendering your page.
None of the above-the-fold content on your page could be rendered
without waiting for the following resources to load. Try to defer or
asynchronously load blocking resources, or inline the critical
portions of those resources directly in the HTML. Remove
render-blocking JavaScript:
https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
Optimize CSS Delivery of the following:
http://fonts.googleapis.com/…%3A300%2C400%7CRaleway%3A400%2C500%2C900
https://www.blogger.com/…/3728782508-widget_css_mobile_bundle.css
https://www.blogger.com/…&zx=88195f1c-da8c-4c99-bb3e-609abb88c4fa
If you've written your page to be dependent on using jquery on load, removing it would mean you'd have to re-write a lot of your code, to save, perhaps 10 milliseconds in load time?
Open your browser's debugger, look at the NETWORK tab and reload the page. You should be able to decide whether this suggested optimization is worth it or not (I'm suggesting it is not).
I was having a similar issue with Javascript. Make sure that in your code after your source your java that you put a type="text/js". Like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/js"></script>
Otherwise you need to go into your server and make adjustments to your htcaccess file.
Heloo Nazmul, may be you should to edit your question to "How to Remove default JS and CSS that make Render Blocking Javascript in Blogger?" may be so long but I think your problem is it.
Follow my step with :
change <head> to <head>
If your Internet Service Provider give some bloking JS and CSS add <!-- </head> --> before </head>
Change </head> to <!--<head/>-->
add <!-- </body></html> --> before </body></html>
It is about DOM get work, I will give you example my blank blogger template if you still headache.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
<meta charset='utf-8'/>
<style/>
<b:skin><![CDATA[]]></b:skin>
<!-- </head> -->
<!--<head/>-->
<body>
<b:section class='header' id='header' showaddelement='yes'/>
<h1 style="color:blue;font-family: monospace">klikada.com</h1>
<b:section class='main' id='main' showaddelement='yes'/>
<b:section class='footer' id='footer' showaddelement='yes'/>
<!-- </body></html> -->
<style>a:link{text-decoration:none;}a:visited{text-decoration:none;}a:hover{text-decoration:none;}a:active{text-decoration:underline;}</style>
</body>
</html>

Javascript at head does not work [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
Given this html code that we are not allowed to edit
<!doctype html>
<html manifest="survey.manifest">
<head>
<title>Offline Survey Application</title>
<link rel="stylesheet" href="styles/survey.css" type="text/css">
<script type="text/javascript" src="scripts/survey.js"></script>
</head>
<body>
<!--should be empty --->
</body>
</html>
<!-- YOU ARE NOT ALLOWED TO EDIT THIS FILE!!! -->
I cannot seem to make my javascript work. But if i placed the script element at the body the whole script shows up. The problem is that we are not allowed to do that though. Is there any other way to make it work?
EDIT: I am aware that the script runs before the other elements are loaded. I can't go with moving it elsewhere since the file would have been modified :/
It could be due to the fact that the script only works when the page has finished loading, but by placing the code in the head, you load the script first. To get around this, you could try replacing your current script code with this:
<script type="text/javascript" src="scripts/survey.js" defer></script>
This ensures that the code only loads once the page has finished loading.
Presumably, your script is attempting to modify the DOM and tries to access the body element.
At the time the script is initially loaded and run, the body does not exist.
Move your code to a function, and bind that code as a load event handler. (addEventListener('load', someFunction);).

<script> tag makes HTML contents disappear

This is such a wierd problem. I have the following extremly simple HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js" />
</head>
<body>
test
</body>
</html>
If I run this page in a web browser, I get nothing at all, just an empty page. If I remove the script reference line entirely, then I get a blank page that displays "test", like it should. This tells me that there is some issue in the jquery.js file, but I have tried 3 different versions of jquery and the one I am using is the latest from the jquery.com website. For the life of me, I can't figure out what I'm doing wrong. I know it will turn out to be simple though.
script tags cannot be self-closing. You need the closing </script> tag:
<script type="text/javascript" src="jquery.js"></script>
Not including the closing tag means the whole content up to and including </html> is treated as the body of the script element. Because the document is then incomplete, your browser closes the script, head and html elements and inserts an empty body element.
you need to close your script tag otherwise it thinks everything after is javascript to be executed...
<script type="text/javascript" src="jquery.js"></script>
The <script> tag is not self-closing, so you'll need a separate </script>:
<script type="text/javascript" src="jquery.js"></script>
See Why don't self-closing script tags work?
You're confusing HTML and XHTML.
In HTML, the script tag is not self closing, so you must write <script src="jquery.js"></script>.
In XHTML, you must set your XML namespace(<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">) and send the document with the correct mime type.

Are there negative effects from not loading jQuery in the <head> tag?

I currently am working on a large site with many different issues to contend with. One being that I have no easy way to include a script into my <head> without manually doing it for 500+ pages.
I have the possibility to include jQuery.min just inside the <body> tag from an include located there.
My question is, aside it not being a standard implementation, would there be any negative effects from not loading jQuery within the <head> tag? Will all the functions be available?
I am aware that if I do this, I will not be able to call jQuery from within the <head> or before this include... that's okay.
example:
<head>
Standard Head Stuff
</head>
<body>
<div>Some Content</div>
<!-- My Include is roughly here -->
<script type="text/javascript" src="jquery.min.js"></script>
<div>More content</div>
<script type="text/javascript">
$(document).ready(function(){
// Put my jQuery commands here
});
</script>
</body>
The only issue is that a page is loaded from top to bottom and so if you were to place the include statement into the header than you would be assured that the library would be loaded immediately. Otherwise the library may only be loaded at a later time which can cause a delay in some effects potentially.
Head or body, inline code will execute when phrased. Code is generally placed in the head so external libraries can be loaded before the page is (so effects can be run on dom ready). Code in the body will be run once the dom is done with the header code, and done loading page elements (once in the body, elements are loaded from top to bottom). So any code in the body will be executed once the page had loaded (up to that point)

Categories

Resources