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);
I am new to JS and programming in general and hope someone can help me with this.
I am currently working on building a website where every page has its separate HTML / PHP file.
jQuery and my global / general JS functions are included in the footer of all these pages through a separate includes file "footer.php".
So far everything works as intended.
Now I have some pages that will use specific jQuery functions so I want to load the corresponding JS only if such a page is loaded.
To do this I saved the corresponding codes in separate JS files (e.g. nameOfExternalJsFile.js) and wrapped everything in there in the following:
$(document).ready(function(){
// ...
});
I then made the following updates to the corresponding PHP pages (example):
<head>
<?php
require_once("includes/header.php");
?>
<!-- here I want to include the specific jQuery functions -->
<script src="includes/js/nameOfExternalJsFile.js"></script>
</head>
<!-- ... -->
<!-- here I include the main JS functions -->
<?php require_once("includes/footer.php"); ?>
I have two concerns with this:
I am not sure if this is the right way of including such files since
I need to have them available on document ready.
I include my main JS in the footer since I was told this improves
performance but can I then include jQuery functions in the header at all ?
Can someone let me know if this is correct or if I should change anything here ?
Many thanks for any help with this.
Wrapping the functions in $(document).ready automatically takes care of this concern. From the JQuery documentation on document.ready.
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute.
Technically it doesn't matter whether you include the scripts in the header or the footer, as long you load JQuery first and your script second.
That said, it's generally recommended that both scripts go just before the closing body tag to increase performance as you suggested. There are some articles that discuss this like this post from performance expert Steve Souders and this guide from the Yahoo! Exceptional Performance team.
You should load the $(document).ready(...) stuff only after you have loaded jQuery, that is, in the footer file, after the jQuery <script> tag, like this :
<script src="includes/js/jQuery.min.js"></script>
<script src="includes/js/nameOfExternalJsFile.js"></script>
It`s good practise to locate all the JS files in the end of the body
<html>
<head></head>
<body>
... Some HTML
<script>SomeScripts</script>
</body>
</html>
</pre>
If you want to be sure that your external scripts are loaded after page load use:
$(function(){
/* Your code from the scripts */
});
You can change the content of footer.php to include /nameOfExternalJsFile.js manually at the bottom of the page. That´s the safest way to do it because you may load jquery before loading others scripts.
I have some HTML files, and each one of them I want to partially render in another HTML file, for example header.html and footer.html in order to observe DRY concept.
HTML files should look like this:
<!--render header.html-->
<div>
Content
</div>
<!--render footer.html-->
How can I do that?
If you're just using plain HTML and Javascript, you could include jQuery and use an AJAX request to load the contend of another HTML page in your main page.
Have a look at the jQuery 'load()' function here:
http://api.jquery.com/load/
Assuming your have the following html:
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
your usage would look something like this:
$('#header').load('header.html');
$('#footer').load('footer.html');
Here's a link (first one from Google I might add) that explains how to do this in various languages.
Also note that some IDEs take care of this for you. Dreamweaver being one example; in ASP.NET there are master pages; and so on.
PHP:
<?php
require($DOCUMENT_ROOT . "path to file/include-file.html");
?>
ASP:
<!--#include file="path to file/include-file.html"-->
JS:
JavaScript is another way to include HTML within the pages of your
site. This has the advantage of not requiring server-level
programming. But it's a little more complicated than the server-level
include methods.
Save the HTML for the common elements of your site to a JavaScript
file. Any HTML written in this file, must be printed to the screen
with the document.write function.
Use a script tag to include the
JavaScript file on your pages.
<script type="text/javascript" src="path to file/include-file.js">
Use that same code on
every page that you want to include the file.
PLEASE NOTE that the JS version is NOT ideal.
1. JS may be disabled or unavailable in the browser.
2. The page won't be rendered/loaded all at once.
Also, I don't think DRY really counts for this one. Consider using an IDE that will create page templates for you (like Dreamweaver for example).
If you are brave enough (and a little bit old fashioned) and you can't use any of the above, consider using an iframe for your content:
<html>
<body>
<div>my header</div>
<iframe src="mycontent.html" />
<div>my fooder</div>
</body>
</html>
DISCLAIMER
I would rather cut off my own hands than implement the iframe or JS approach. Give deep consideration towards whether you actually NEED to do this.
If you are looking for a client side only solution that is html/js only you should have a look at AngularJS and its ngInclude syntax.
http://docs.angularjs.org/#!/api/ng.directive:ngInclude
If you are using server-side programming, you can use server-side include else if your host file is an HTML file then you can use html SCRIPT tag to include the header.html and footer.html files. Though, am not sure as to what do you really mean by partially rendering HTML file?
As others said, it looks like it can't be done with HTML alone. Another way it could be done on the server-side, if you are using Java, is with Thymeleaf.
For example, adding a main menu on every page with
<div th:replace="fragments/mainmenu.html"></div> . Then mainmenu.html could just contain a bunch of divs. The fragment doesn't need to be a full HTML page.
Hey guys. I don't do HTML or Javascript, I prefer to work in C#, but one of the JS guys tells me that he needs a script included within the head tag. The page in question is a content page of a master page. I can't seem to make this work. I tried adding the script by a programmatic reference this.ClientScript.RegisterClientScriptInclude, but it came out in the <body> tag. I tried adding a ScriptManager and a ScriptReference in the contentplaceholder inside the <head> tag of the master page, but this didn't work either. How can this be accomplished?
Just put a client side reference to the script in.
<head> <script lang="Javascript" src="./scripts/yourscript.js"></script>
Or, if it needs to be inline, include the actual script right there in the master page.
I was reading a tutorial and the author mentioned to include JavaScript files near the closing body tag (</body>) in HTML.
For what type of functionality should I not declare/define JavaScript include in the head section? It makes sense to me include JavaScript like Google Analytics near the closing body tag. Where should I be careful in defining JavaScript include near the closing body tag?
It will often be argued that for speed purposes you should put script tags right at the end of the document (before the closing body tag). While this will result in the fastest page load, it has some serious downsides.
Firstly, a common idiom with Webpage development is to have a header file, a footer file and your content in the middle. To keep unnecessary JavaScript code to a minimum, you'll often want to put code snippets in individual pages.
If you include jQuery, for example, at the end of the document, your jQuery code snippets (like document ready stuff) must happen after that. That can be awkward from a development point of view.
Secondly, in my experience, because the page load is faster, you can end up noticing certain effects being applied because the page has already loaded by the time they are applied.
For example, if you put a table in a document and right before the body close tag put:
$(function() {
$("tr:nth-child(odd)").addClass("odd");
});
with appropriate styling, that effect being applied will often be visible. Personally I think that makes for a bad user experience potentially. I think often you're better off having the page load slightly slower (by putting scripts at the top) if you don't get disconcerting visual effects.
I generally advocate effective caching strategies so you only have to download JavaScript files when they change, as in Supercharging JavaScript in PHP (but the principles apply to any language, not just PHP) and still putting scripts at the top. It's far more convenient.
By putting them in the <head/> you force the browser to download the files before it can render a page. That causes the perceived load time to slow down.
By placing them in the footer, right before the closing body tag, the browser will not load them until it reaches that point in the parsing of the HTML. That means that the scripts will run later in the page load process but will not block the asset download and rendering process.
Which works best is up to you and how you develop your code.
The Yahoo YSlow tool has advice on this:
The problem caused by scripts is that
they block parallel downloads. The
HTTP/1.1 specification suggests that
browsers download no more than two
components in parallel per hostname.
If you serve your images from multiple
hostnames, you can get more than two
downloads to occur in parallel. While
a script is downloading, however, the
browser won't start any other
downloads, even on different
hostnames.
In some situations it's not easy to
move scripts to the bottom. If, for
example, the script uses
document.write to insert part of the
page's content, it can't be moved
lower in the page. There might also be
scoping issues. In many cases, there
are ways to workaround these
situations.
An alternative suggestion that often
comes up is to use deferred scripts.
The DEFER attribute indicates that the
script does not contain
document.write, and is a clue to
browsers that they can continue
rendering. Unfortunately, Firefox
doesn't support the DEFER attribute.
In Internet Explorer, the script may
be deferred, but not as much as
desired. If a script can be deferred,
it can also be moved to the bottom of
the page. That will make your web
pages load faster.
Google pagespeed have some nice explanation on how to parallelize downloading of scripts.
Still their advice is to put them in the head of your page.
Script tags should generally be in the head section. The exceptions are when they do significant immediate processing that should be delayed until as late as possible in the page load to avoid interfering with the page coming up, as with Google Analytics, or when the script tag's actual placement is a part of its behavior.
The reason for declaring near the end is that your page can begin drawing before having to wait to fetch the .js.
Ergo, stuff you would want at the end would have no effect on the page rendering, and vice versa.
I like to load a small js file in the head, that handles (1) anything that happens before the page is rendered and (2) the loading of other script files after the page loads, or as needed.
The Place of the <script> Element
The script elements block progressive page downloads.
Browsers download several components at a time, but when they encounter an external script, they stop further downloads until the script file is downloaded, parsed, and executed.
This hurts the overall page time, especially if it happens several times during a page load.
To minimize the blocking effect, you can place the script element toward the end of
the page, right before the closing tag.
This way there will be no other resources for the script to block.
The rest of the page components will be downloaded and already engaging the user.
The worst antipattern is to use separate files in the head of the document:
<!doctype html>
<html>
<head>
<title>My App</title>
<!-- ANTIPATTERN -->
<script src="jquery.js"></script>
<script src="jquery.quickselect.js"></script>
<script src="jquery.lightbox.js"></script>
<script src="myapp.js"></script>
</head>
<body>
...
</body>
</html>
A better option is to combine all the files:
<!doctype html>
<html>
<head>
<title>My App</title>
<script src="all_20100426.js"></script>
</head>
<body>
...
</body>
</html>
And the best option is to put the combined script at the very end of the page:
<!doctype html>
<html>
<head>
<title>My App</title>
</head>
<body>
...
<script src="all_20100426.js"></script>
</body>
“JavaScript Patterns, by Stoyan Stefanov
(O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”
You should put JavaScript right before </body>. Ideally, your HTML should function without JavaScript, so it should be one of the last things loaded.
Bear in mind that you should use CSS to hide elements and not JavaScript. This avoids seeing elements appear and disappear as the page loads.
You may also come across the following problem...
Problem
In this scenario, I'm going to use PHP as an example.
Your footer.php file may currently look like this:
<script src="jquery.js"></script>
<script src="custom.js"></script>
</body>
</html>
But what happens on the rare occasions you want to add some <script> exclusively for one page? You wouldn't be able to put it after footer.php because you wouldn't be in the <body> tag anymore, but you can't put it before, because then you'll be missing the jquery.js from your code.
Solution
Have a footer-start.php file:
<script src="jquery.js"></script>
<script src="custom.js"></script>
And a footer-end.php file:
</body>
</html>
And have your footer.php be simply:
<?php
require 'footer-start.php';
require 'footer-end.php';
Then, on the rare occasions that you need to use a custom <script> for one page, do this:
<?php require 'footer-start.php'; ?>
<script>...</script>
<?php require 'footer-end.php'; ?>
Doing it this way means you don't have to change all your previous code where footer.php is referenced.
I believe it's better to place script tags just before the closing body tag. Because:
Elements are blocked from rendering if they are below the script.
In Internet Explorer 6 and Internet Explorer 7, resources in the page are blocked from downloading if they are below the script.
It is from this article. Also Yahoo's performance rule 6 is Move scripts to the bottom.
You should do it near </body>. The reason is simple: If you place it into the head area, the files must be loaded before the body area can be. For that time, the user just sees a white screen.
But it depends on your website. I would load frameworks like mootools in the head area, other functions for events or AJAX or something should be loaded near </body>.
The only reason for putting it near the end of the body, AFAIK, is to be able to execute the JavaScript after the web browser has parsed your HTML document. E.g. if your JavaScript deals with "all elements named hello", the browser needs to read the entire document before executing your JavaScript. Makes sense, right?
In e.g. jQuery, you can put your JavaScript anywhere in your document and use:
$(document).ready(function () {
// Your code here
});
...to make sure the entire document has been loaded into the DOM before executing the inner function. Of course, this can be done with normal JavaScript as well, but be careful not to break compatibility with some browsers, because their needs tend to differ a lot.