Is it OK to put javascript code anywhere in HTML code? - javascript

I see that Javascript code is normally in heading part of HTML code.
<head>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</head>
Is it OK to put the Javascript code in a body part of HTML code? I tested it, but it seems to work.
<body>
<script type="text/javascript" language="javascript" src="core.js"></script>
...
</body>
If so, why the examples of Javascript books put the javascript code in heading part?
If not, what's the difference between putting the javascript code in body/heading part?

Not only is it OK, it's actually better, since it lets the content come first.
If your viewers have a slow (eg, mobile) connection, it's better to send the actual content first, so that they can read it while the browser downloads the Javascript.

All the people saying it is better only applies if you are talking about at the bottom of the page (and that is an up for debate thing) from a code quality point of view, it is NOT ok to sprinkle script tags through your html. All references to javascript should be in a single place on the page, either the head (where they should be), or the very bottom (as a perf optimization)
Edit:
Basically, a web page is made up of 3 pieces; style (css), structure (html), and behavior (javascript). These pieces are all very distinct, so it makes sense to keep them as separate as possible. That way if you need to change some javascript, it is all in one place. If it is sprinkled through the file, it becomes much more difficult to find the code you are looking for, and that code basically becomes noise when you are just looking at structure.
It is the same arguments as why not sprinkle db access code all over your page. It has nothing to do with technical reasons, purely an architectural/design decision. Code that does different things should be kept separate for readability, maintainability, and by extension, refactorability (not sure if that last one is actually a word...)

You can do it, and people often do.
For example, people like to put their script tags just before the closing </body> to make web pages render quicker.
Also, if you do a script block after an element is created, you don't need to wait for DOM ready.
Be warned though, don't add, or remove an element from an unclosed ancestor in the markup tree (not including the script block's immediate parent element), or you will get the dreaded Operation Aborted error in IE.

Just something to add on:
I have preference of putting Javascript file right before </body>. My reasons being that:
Content can load and be shown first. If you load huge Javascript files first, which most are meaningless until the page is loaded, the user won't be able to see anything until the JS files are loaded.
Most Javascript code require to work with the UI can only run after the UI has been loaded. Placing the codes at the end of the html file reduces the need to use the onload event handler.
It is very bad habit to place Javascript snippets all over the HTML file. Placing all at the back of the HTML file allows you to manage your Javascript more efficiently.

It is legal according to the spec.
Most examples use them in the header as the headers come first and the browser will be able to parse the reference and download the JS files faster.
Additionally, these are links and are not part of the display, so traditionally, put in the header.

It is perfectly legal but there seem to be some differing opinions about it. Those who say to put all the javascript references in the head argue that the script is downloaded before the rest of the page become visible and dependent on it. So your user will not see an object on screen, attempt to interact with it and get an error because the javascript code is not yet loaded.
On the other hand, the argument goes that it takes longer to load all the script before the user sees the page and that can have a negative impact on perceived speed of your site.

JavaScripts inside body will be executed immediately while the page loads into the browser
Placing javascript at the end of the body will defer javascript load (ie: the page will render faster), but remember that any javascript function used for an event should be loaded before the event declaration, it is mainly because users may be able to fire an event before the page is completely loaded (so before the function is loaded)!

I used to put it in the head, then I've heard that it takes longer for the page to load so I started placing the scripts at the very bottom. However, I found out the most 'clean' way to do it is to place it in the head BUT you place the script inside a document.ready function. This way you have the best of both worlds. It is cleaner because it is in the head and it is not loaded before the content has been loaded, so there aren't any problems performance wise either.
With jQuery for instance, you can do it like this:
$(document).ready(function() {
alert('test');
});
The alert will only popup when the page has been fully loaded, even though the script is in the head.

Related

The difference between async loading js files and loading in footer [duplicate]

Where is the best place to put Jquery code (or separate Jquery file)? Will pages load faster if I put it in the footer?
Put Scripts at the Bottom
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.
EDIT: Firefox does support the DEFER attribute since version 3.6.
Sources:
http://www.w3schools.com/tags/att_script_defer.asp or better:
http://caniuse.com/#feat=script-defer
All scripts should be loaded last
In just about every case, it's best to place all your script references at the end of the page, just before </body>.
If you are unable to do so due to templating issues and whatnot, decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="my.js" type="text/javascript" defer="defer"></script>
Edge cases
There are some edge cases, however, where you may experience page flickering or other artifacts during page load which can usually be solved by simply placing your jQuery script references in the <head> tag without the defer attribute. These cases include jQuery UI and other addons such as jCarousel or Treeview which modify the DOM as part of their functionality.
Further caveats
There are some libraries that must be loaded before the DOM or CSS, such as polyfills. Modernizr is one such library that must be placed in the head tag.
Only load jQuery itself in the head, via CDN of course.
Why? In some scenarios you might include a partial template (e.g. ajax login form snippet) with embedded jQuery dependent code; if jQuery is loaded at page bottom, you get a "$ is not defined" error, nice.
There are ways to workaround this of course (such as not embedding any JS and appending to a load-at-bottom js bundle), but why lose the freedom of lazily loaded js, of being able to place jQuery dependent code anywhere you please? Javascript engine doesn't care where the code lives in the DOM so long as dependencies (like jQuery being loaded) are satisfied.
For your common/shared js files, yes, place them before </body>, but for the exceptions, where it really just makes sense application maintenance-wise to stick a jQuery dependent snippet or file reference right there at that point in the html, do so.
There is no performance hit loading jquery in the head; what browser on the planet does not already have jQuery CDN file in cache?
Much ado about nothing, stick jQuery in the head and let your js freedom reign.
Nimbuz provides a very good explanation of the issue involved, but I think the final answer depends on your page: what's more important for the user to have sooner - scripts or images?
There are some pages that don't make sense without the images, but only have minor, non-essential scripting. In that case it makes sense to put scripts at the bottom, so the user can see the images sooner and start making sense of the page. Other pages rely on scripting to work. In that case it's better to have a working page without images than a non-working page with images, so it makes sense to put scripts at the top.
Another thing to consider is that scripts are typically smaller than images. Of course, this is a generalisation and you have to see whether it applies to your page. If it does then that, to me, is an argument for putting them first as a rule of thumb (ie. unless there's a good reason to do otherwise), because they won't delay images as much as images would delay the scripts. Finally, it's just much easier to have script at the top, because you don't have to worry about whether they're loaded yet when you need to use them.
In summary, I tend to put scripts at the top by default and only consider whether it's worthwhile moving them to the bottom after the page is complete. It's an optimisation - and I don't want to do it prematurely.
Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.
Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.
In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.
Just before </body> is the best place according to Yahoo Developer Network's Best Practices for Speeding Up Your Web Site this link, it makes sense.
The best thing to do is to test by yourself.

JavaScript in <head> or just before </body>?

I am about to embark on a new web project and I plan to put some JavaScripts in the <head> and also some before </body>, using the following scheme:
Scripts that are essential for the UX of the page: in the <head>. As I've picked up perusing the web - scripts in the <head> is loaded before the page loads, so it would make sense to put scripts that are essential to the user experience there.
Scripts that are non-essential to the design and UX (Google Analytics scripts etc.): before the </body>.
Is this a sensible approach?
Another approach would be to put all the scripts in the <head> and add defer attributes to the non-essential scripts. However, I read that older versions of Firefox don't pick up the defer attribute.
I think a lot of developers run JavaScript just before the </body> so that it is run after all the elements have been rendered.
However, if you organise your code correctly, the position on the page doesn't matter.
For example, when using jQuery, you can ensure the code isn't run until the page and its elements are fully rendered by doing the following:
$(document).ready(function(){
//Code here
});
Then the script reference can be put in the head tag.
Script tags should be referenced just before </body>. This prevents render blocking while the scripts load and is much better for site perception speed.
No obtrusive JavaScript should be used when using this technique.
JavaScript code should be placed at the end of the document so that it doesn't delay the parallel loading of page elements. This does then require that the JavaScript code is written in a specific way, but it does improve the speed of page loads.
Also, ideally you could host references like this under a different (sub)domain. References to jQuery should be pointed to Google's CDN too.
See Best Practices for Speeding Up Your Web Site for more information.
One of the reasons you'd want to put scripts before the </body> is if they manipulate the DOM without user interaction, so you'll need the DOM to be loaded in order to be manipulated. Another way to do that is to add an event listener and run the scripts when the page has loaded, but this will require additional code, which might get complicated if you have a lot of scripts, especially ones you haven't written yourself. Putting them at the end of the page also will speed up page load, though in the case of DOM manipulating scripts you might get some not-so-pretty results from that.
I'd say that's perfectly sensible. As you said, as long as you don't move essential scripts (e.g. jQuery, Modernizr, etc., etc.) out from the <head>, you shouldn't have problems.
Moving non-essential scripts to the bottom of the page should help with the perceived loading speed (that and minimizing / concatenating scripts).
It all depends on what you mean by "essential for UX". I agree with having Modernizr appear early for example, but not everything needs to load straight away. If you're trying to avoid a flash of unstyled text (FOUT), that's a good reason. Similarly, if you have scripts that affect how the page looks before the user does anything, you should load those early.
Don't forget though, speed is part of UX. There's no advantage in having some jQuery interaction ready to run when the user can't see the content it applies to yet. The difference between loading the scripts at the start of the end is a matter of seconds. If you let the page load first, the user will be using those seconds to take the page in, allowing you to load scripts unobtrusively.
Your page will load faster if you move scripts to the bottom of the page, and that makes a difference to your pagerank these days.
Also, some versions of Internet Explorer will throw errors if you try to run a script before the element it refers to has loaded.
Like Ed says, your scripts should be stored in a separate file, and in as few files as possible.
Put the JavaScript code in a separate file and place a link to it in the head part of the HTML.

If Javascript code block is not at end of HTML file, but is using jQuery's $(document).ready(function() {...}), will it slow down the page display?

It is said that Javascript code should be all placed at the end of HTML file, so that the page content is shown first, for the user to see something (so that the user is satisfied to see something instead of waiting another 12 seconds, for example).
But to better encapsulation of the HTML and match Javascript code, such as an "Image Carousel", then usually the HTML and Javascript is placed in one single file, so there are Javascript code blocks all intermixed with HTML code throughout the final HTML file.
But what if all these Javascript code blocks use jQuery's $(document).ready(function() { ... }) to perform the task, then won't the page display be very fast as well? I think not as fast as when the Javascript is actually placed at the end of the HTML file, but close enough, because it merely adds a function to the ready event queue.
I think the point is to place the js at the bottom of the page (usually just inside the closing </body> tag) so that the content of the page is displayed while the js is downloading.
If you have your jQuery code spread out throughout the HTML in separate .ready() calls, then no matter what, it won't run until the <body> has fully loaded. So the question would be how much javascript do you have in the HTML?
If there's quite a bit, then it will slow down the display of any content that comes after each script. If it is a relatively small amount of code, then it won't likely make much noticeable difference.
If it is really important to you to have the page's content displayed as soon as possible, then place all scripts after the content.
I personally wouldn't mix javascript with HTML just for the sake of association. You could have unexpected results if you start removing/appending content that happens to include a script. I'd rather use appropriately named classes and IDs, as well as lots of code comments.
Also keep in mind that those .ready() calls won't work until jQuery has loaded, which would mean that it would need to be at the top of the page, or at least before your first call.
So again it gets back to the question of which is more important to you. If you want the content visible as quickly as possible, place all js at the bottom. If you want your method of intermixing js and HTML, you'll have some delay in displaying the page.

Optimal location for javascript includes

I've read that it is better to place your <script> tags at the end of the document. The argument for doing this appears to be that the browser will stall rendering the page below a script tag until it has loaded and and executed the script. If your script tag is at the top of the page, rendering is stalled for a while, which is bad.
However, I am not sure if this is really true any more.
Looking around, I normally see the following locations...
In the <head> of the page or Just inside the <body> tag
Stackoverflow is an example of a site that puts the script tags in the head, and since they are normally rather obsessed with performance, I am starting to wonder if position in the page is important at all.
Last thing in the body element
The other common place to put javascript appears to be right at the very end of the <body> element. I am assuming this means that the page can render while the javascript downloads and gets on with doing its thing.
But which is better?
Does anyone have any thoughts or advice on this? I am looking to try and get our pages to perform and appear to the user as quickly as possible.
Does it matter? What are the advantages of being at the top of the page? Bottom of the page?
It really depends.
There is no catch all answer for this because it depends on what your javascripts are acting on.
Putting scripts at the end of the page is sometimes needed if your acting on a DOM element that needs to be loaded for the script to run. Say you want to focus on a control and your script is:
var mytext = document.getElementById("mytext2");
mytext.focus();
Well in this case you would want it to execute at the end of the page, after mytext2 control has already been loaded by the browser. This is less important for script blocks that only contain functions that are called by events.
If you have a big .js file that contains libraries of functions you may also want to put that at the end of the page so the browser will load the page faster before loading the large .js file.
Google analytics suggests putting their tracker at the end, to make sure the page has been delivered before you count the hits, but in some cases it suggests putting the script into the header too, it works both ways.
So, rule of thumb for me is, HEAD scripts for everything except things that execute in-line and act on DOM objects, or large scripts that you want to load after the page.
Rick Strahl just wrote a great blog on placement of Javascript in .net too:
The only validating way is to include it on the top (in the <head> section), but in the bottom will be faster to load - the rest of the page will load faster if you have script near the bottom, giving the user better response and making the experience better.
The problem is that most web browser stop rendering the HTML of the page until they've fetched and parsed all JavaScript code so far. So if you have a slow-loaded .js file included in the <head>, no HTML will be rendered and images will not even start to download before the .js have been downloaded and parsed, therefore frontend engineers propagate for putting the scripts as far down in the code as possible.
I usually just set a far-future Expires header for my .js files so they are cached in the browser for a long time and then include them in the <head> section. This gives good performance and doesn't look ugly :-)
But if you are serving external .js libraries (that are on other servers than your own), you will probably want them in the bottom because you can't change the Expires-header for other servers and you canät know that the other server always will be responsive.
yeah. Put Scripts at the Bottom
I think the size of the js file is much more important than the location of javascript. I always set highter number of the con-current connection to make sure they download in parallel.
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 IE6, IE7 resources in the page are blocked from downloading if they are below the script.
From this article. Also Yahoo's performance rule 6 is Move Scripts to the Bottom
Google Analytics always used to say to put the script tag at the bottom of the page. I believe the rationale was that if the Google servers ever went down, the page would fail to load if it were in the head (only for IE probably).

Programmatically remove <script src="/unwanted.js".. /> reference

I have partial control of a web page where by I can enter snippets of code at various places, but I cannot remove any preexisting code.
There is a script reference midway through the page
<script src="/unwanted.js" type="text/javascript"></script>
but I do not want the script to load. I cannot access the unwanted.js file. Is there anyway I can use javascript executing above this refernce to cause the unwanted.js file not to load?
Edit: To answer the comments asking what and why:
I'm setting up a Stack Exchange site and the WMD* js file loads halfway down the page. SE will allow you to insert HTML in various parts of the page - so you can have your custom header and footer etc. I want to override the standard WMD code with my own version of it.
I can get around the problem by just loading javascript after the original WMD script loads and replacing the functions with my own - but it would be nice not to have such a large chunk of JS load needlessly.
*WMD = the mark down editor used here at SO, and on the SE sites.
In short, you can't. Even if there is a hack, it would heavily depend on the way browsers parse the HTML and load the scripts and hence wouldn't be compatible with all browsers.
Please tell us exactly what you can and cannot do, and (preferably; this sounds fascinating) why.
If you can, try inserting <!-- before the script include and --> afterwards to comment it out.
Alternatively, look through the script file and see if there's any way that you could break it or nullify its effects. (this would depend entirely on the script itself; if you want more specific advice, please post more details, or preferably, the script itself.
Could you start an HTML comment above it and end below it in another block?
What does the contents of unwanted.js look like?
You can remove a script from the DOM after it is called by using something simple such as:
s = document.getElementById ("my_script");
s.parentNode.removeChild(s);
This will stop all functions of the script but will not take it out of user's cache. However like you wanted it can't be used.
Basically you can't unless you have access to the page content before you render it.
If you can manipulate the HTML before you send it off to the browser, you can write a regular expression that will match the desired piece of code, and remove it.

Categories

Resources