NOTE: I am in no way advocating multiple heads within a page
I'm using Apache Tiles and I have a few tiles that include their own heads. The result of the Tiles renders into an HTML page with multiple heads.
My questions:
How is the resulting page handled in IE and Chrome? [It renders and appears successful]
WITH APACHE TILES What is the best practice for dealing with/avoiding multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS files.
For Example with Question Two:
Lets say you have the following pages: home, profile, and gallery listing. Gallery listing has fancy JQuery+YUI+... and more styles. For most users, they would only be interested in the home and profile pages, so why slow them down with loading the JS and CSS files associated with Gallery.
This is what is generated
<html>
<head>
<title>The Template's Title</title>
</head>
<body>
<head> <script src="javascriptfile.js"/></head> Tile One Content
<head> <script src="javascriptfile2.js"/></head> Title Two Content
</body>
</html>
The generated contents is running the script in javascriptfile.js, and javascriptfile2. What I'm asking in the first question: is the extra heads ignored, and the contents considers? are they combined into the html/head level? Is it possible to include CSS files in the second or later head? Will this create an error with a stricter DTD?
Well, in modern Chrome, it's at least possible to know what happens. Chrome uses the HTML5 parser algorithm which describes exactly how invalid mark-up is processed. The gory details are at http://dev.w3.org/html5/spec/tree-construction.html#parsing-main-inbody
What happens in your example is that the first <head> in <body> is discarded. Then the <script src="javascriptfile.js"/> tag is processed, which is a start tag, not a self-closing tag, so everything that follows, including everything that looks like a tag, becomes a text child of the script element. Nothing is displayed and no script is run. If <script src="javascriptfile.js"/> is replaced by <script src="javascriptfile.js"></script>, and ditto for <script src="javascriptfile2.js"/>, the head start and end tags are silent discarded, and the script elements are not moved. "Tile One Content Title Two Content" is displayed and the scripts are run. The DTD makes no difference at all.
IE is somewhat trickier to know, as before IE10, it doesn't use the HTML5 parser algorithm and therefore it's exact behaviour is a mystery. However, a cursory experiment appears to show that it has the same behaviour as described above.
Although some legacy browsers move elements that can only appear in the head - such as <link> - into the head, other browsers do not, and no such behaviour can be relied upon.
All in all, best steer well clear of such constructs.
I don't know about practices for Apache Tiles.
What is the purpose of doing something so egregiously invalid? And why you're asking this seems very unclear.
Not only should you only have ONE <head></head> section on a page, under no circumstances is the <head></head> to be nested anywhere inside the <body></body> section.
This practice makes absolutely no sense whatsoever....
(Side-note: Certain browsers ignore or move invalid tags when the DOM is constructed which will defeat your entire purpose of doing this.)
EDIT (based on comments):
For anyone interested in including <script> tags within the <body>, you can read more about the specific details in my answer here...
Will linking javascript files in the body rather than in the header cause a problem?
You don't really need extra heads to include additional css/js. You can 'inline' the whole <style type="text/css">...</style> part and it will render fine. Will it validate? No. But will run fine.
How is the resulting page handled in IE and Chrome? [It renders and appears successful]
I don't know and I really don't want to know.
What is the best practice for dealing with multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS.
Don't do it :-)
Is there a reason you can't just include the JS files in the body / head without the extra tags?
Or add the css / js files in the 'normal' head section of the document (where it should be).
Well atleast you want the CSS files to be loaded as soon as the page starts loading. JS files can (sometimes) be loaded at the end of the HTML.
For example if the JS files need to have a completely loaded DOM (for e.g. accessing DOM elements).
Note
Sorry this isn't really an answer to your question, however what you are doing just looks way bad. :) And is almost certainly not needed / there will be a better solution for it.
Related
I need to implement javascript and css resources for the framework I'm working on, but I have a BIG concern.
If you take a look at current websites like Facebook, Google, Youtube and other top-tier sites, their source code show their usage of javascript in various places in the code. The first question coming into my mind is... isn't supposed for javascript source files to be allocated at the beginning of the document? You can/should be able to place javascript commands enclosed in script blocks, but... source files, too??
The books I've been reading suggests (as best practices, I guess) all source files should be allocated in the head section, while displacing all code blocks to the end of the page, right before closing the body section (when possible).
Same applies for CSS. I've seen pages where, in the middle of the page, you find a source file inclusion, while the normal declaration is to include all css files in the beginning (as it's more efficient than in-place inclusion because they load in parallel that way).
In my thoughts, and if I'm to follow the books I've been reading, source files (both javascript and css) go always on top, script blocks (when possible) go to the bottom part of the document and CSS inclusions are to be avoided in-place (except for when you want to use the scope attribute or it's a style declaration inside an html tag, which should also be avoided when possible).
Is that right?
Best practice dictates thus:
CSS files should go into the <head> of the document, as near to the top as possible. I usually place mine after any <meta> tags.
JavaScript files should go as close to the end of the <body> as possible, usually directly before the </body> tag.
This is because JavaScript files load serially and are blocking, so if JavaScript files are included in the <head> of a page, all files must load in their entirety before the main body of the document can load, which often creates the perception of a delay.
Really, there is little difference between JavaScript files and JavaScript script block. They both use the <script> element, it's just that externally referenced files have an src attribute. From the point of view of the parser, they are the same.
From a validity point of view, <script> elements may be placed anywhere in the <head> or <body> of a page, and there are times when <script> files should go in the <head>, such as when using something like typekit, as this will ensure font files are loaded in time for the fonts to be displayed as soon as the page has loaded, preventing a FOUF (flash of unstyled font)
I mean : I know the JS is cached only if it come from a .js file. Also, 90% of my functions must be rendered when the page (html) is loaded (rendered), so it is better put JS before closing the body tag. (this prevent also to use document .ready(); and the loading of the page itself will be more faster).
So, which is the advantage on putting JS in the <head></head>? Expect the "order" of the code, which I don't mind so much to be honest...
Placing a <script src> tag inside the <head> section makes sense – semantically. It does block the browser from rendering anything until the script is loaded but assures that an object (e.g. jQuery) is available in the rest of your code (in the body for example).
A common practice is to load a light weight script loading library (HeadJs, LABjs, etc) inside the head section, then load the heavy stuff lazily and/or on-demand.
Having said that, HTML5 introduced the async attribute for script tags and re-introduced the defer attribute (docs). So you now have a very good and valid reason for putting <script src> tags inside head sections because:
it makes sense
the script still loads after the page has finished loading
The <script> tag causes two problems:
Everything below the script won't render until the script is loaded.
All components below the script don't start downloading until the script is done.
Putting it into the <head> only really makes sense if you need to execute some JavaScript before anything gets rendered.
So placing it as low as possible in the page would result in a better user experience.
It's slightly more semantic to put it in the header, but it doesn't generally have any advantages. Sometimes it is necessary - for example, loading fonts using JavaScript (using stuff like Google Webfonts) has to be done in the header, or the page will render with the wrong font and then change, which won't look good to the user.
The important thing about the elements in the <head> section are that they are loaded, before the <body> starts to load.
This is a very efficient feature, which are used a lot (IMO).
Loading of libraries, scripts, that have to run before the DOM has loaded have to done in <head> section.
I will give you a scenario
Imagine, You needed to calculate the 30% size of the screen's total size and assign it to the element inside.
It would be foolish and wait for the element to load big, then run the script to load resize it again.
Apologies for the dumb sounding question, but I need the experts to clarify.
Out of the three places to put JavaScript, head, $(document).ready, or body, where would the best place be to put some ajax that uses a lot of $GET functions?
For instance I am using a JavaScript function called execute_send() but I am unsure where the best place to put it would be. Below is the error:
Problem at line 67 character 22: 'execute_send' was used before it was defined.
function execute_send() {
Also how does the placement affect the page loading time?
In general, unless for some reason you need it elsewhere, put all of your JS last in the body. The browser won't continue until it's parsed your JS, so it is nice to let the page load first. See http://developer.yahoo.com/performance/rules.html
As an example of when you might actually want to put JS in the head: You might have some A/B testing code that you want to run before the page even renders - in that case, the code should go in the head, because you really do want it to run as soon as possible.
As #Thom Blake said, in general the best place is at the bottom of the <body> (+1 for that) - but I'll expand on that a bit:
The reason for this is that as the browser loads the page, it has to stop loading and parse the JavaScript when it encounters it. So if you have all your scripts in the <head> for instance, there will be a delay in loading all the content in the <body>
Note that this is a delay in loading - separate from the actual execution of the script. Something like $(document).ready() deals with when the script is executed, not with when it is loaded.
Generally, all this matters because you want a web page to feel as responsive as possible, so a best practice list for JavaScript will usually be along these lines:
Place all your scripts at the bottom of the <body> so that the loading of non-JS resources, such as images, is not delayed.
Combine your scripts into a single file, so that the server has to make fewer requests for resources (you'll see this referred to as "minimizing HTTP requests")
Minify you scripts, to reduce their total size, which speeds up loading times
Put any code reliant on the DOM (eg click handlers, HTML manipulation, etc) inside $(document).ready() (or the equivalent method for the JS library in use on the page).
Same subject : whats-pros-and-cons-putting-javascript-in-head-and-putting-just-before-the-body
In the past, i experienced some jquery problems has it was not 'loader' when initialising .. this is why we decided to insert it in the <head>.
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.
For the rest of javascripts, all before the closing </body> tag.
To explain the 'Why page will load faster' : It wont.
Browsers are single threaded, so it’s understandable that while a script is executing the browser is unable to start other downloads. But there’s no reason that while the script is downloading the browser can’t start downloading other resources. And that’s exactly what newer browsers, including Internet Explorer 8, Safari 4, and Chrome 2, have done.
The difference is visible has your ressources within the <body> tag will load/show sequencialy. When the browser gets to load <script src=...js> the complete file has to be loader before the browser can fetch another ressource. So, it's an illusion, because the browser will load/di more 'visible' content before 'javascripts'.
To visualise the whole thing : firebug > Net (tab)
As stated before, $(document).ready is not a place. (For jQuery, $(document).ready simply ensures that the DOM is fully loaded (ready to manipulate) before any script is executed.) You would place your JavaScript in the <head> or the <body>.
However, putting all of your JavaScript includes and JavaScripts at the bottom of the <body> section is best for loading performance. "Progressive Rendering" and "Parallel Downloading" are blocked for everything below the scripts. If your scripts are the last thing on the page, you're not blocking anything.
This article explains it in more depth.
Example:
<html>
<head>
<!-- MY HEAD CONTENT - LOAD ALL CSS -->
</head>
<body>
<!-- MY HTML CODE -->
<!-- START javascript -->
<script type="text/javascript" src="/ajax/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/ajax/jquery/plugins/jquery.random_plugin.js"></script>
<script type="text/javascript" src="/includes/some_other_scripts.js"></script>
<script type="text/javascript" language="JavaScript">
//<![CDATA[
$(document).ready(function(){
// my jQuery/JavaScript code
});
//]]>
</script><!-- END javascript -->
</body>
</html>
I'm creating an AJAX heavy web application and I'm curious on what people's thoughts are on adding style and script tags to the body of an HTML document.
I've been using the jquery.load() method to insert content on the fly. An example partial HTML page that could get loaded into the body element is this:
<script type="text/javascript">
$(function() {
// All required java script for the control goes here...
});
</script>
<style type="text/css">
/* All required styles for the inserted HTML go here */
</style>
<div id="some-control">
<!-- Required HTML markup is here. -->
</div>
Since this HTML is getting loaded into a DIV, we are ending up with script and style tags that are not in the head but in the body of an HTML document. I'm not sure if this is valid HTML? Is this a common approach to developing AJAX enabled web applications? Are there any drawbacks I should be aware of?
As far as Javascript is concerend, you can put it any where on the page provided that elements it will work upon are loaded before and it does not throw the error undefined element. Famous Yahoo performance article and even Google (in terms of SEO) suggests to put javascript at the end of the page just before the </body> tag.
If you can manage to put your script just before </body> tag, that is considered good approach otherwise what you are doing now should be fine if everything is working properly for you.
I would actually disagree with Sarfraz and say that you should avoid using <script> and <style> tags in your page body as much as possible. The advantages of moving your JS to an external file are endless. The most obvious include:
leveraging on browser caching - if you just write code in your body, that's extra kilobytes of data that need to be loaded for every page. If it's a universal function, you're wasting precious load time. If it were in an external file, most modern browsers cache that file and only request a new version so often. This decreases server load as well (less requests)
Furthermore, if you ARE using a similar script on multiple pages, what happens if you need to make a change :(. Now you're running around searching for every instance of a <script> tag to make a change. Having all your code centrally located and universal allows for ONE change and DONE
Versioning - if you use version control (GIT, SVN, etc), it's much easier to track and revert one file (if you made a mistake or accidentally lost code) than all of them
CSS share a similar story. Again, with caching and centralized storage, and reusability. It's even more important, however, for styles to match on a website. From a UI standpoint, you don't want your fonts changing from page-to-page and you don't want to edit 40 pages every time you want to add a new style.
As far as having the JS in the document because you are using AJAX loaded content, I suggest you look into .bind and .live. They let you attach handlers to existing and future instances of a DOMObject. For example:
$('.class').live('click', function(){
alert('I was clicked!');
});
This will apply to any object that existed at page load AND objects that are later created. The following code will NOT - it only applies to objects created on load:
$('.class').click(function(){
alert('I was clicked!');
});
When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.
Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.
If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.
Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.
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.