Add one external js file for everything? - javascript

I have an HTML page that I want to perform several lines of js code on. For now I'm just trying one thing:
document.getElementById("title").style.color = "blue";
This is in jsPage.js the within the head of my html page I have
<script src="jsPage.js"></script>
I thought this was all that was necessary. But my title is staying red (this is what it is set to in the css doc attached to html page) instead of turning blue. Am I missing some standard declaration or something in the js file?

Assuming that document.getElementById("title").style.color = "blue"; is in jsCalc.js, you're most likely not changing the text color after the window loads.
The content of jsCalc.js should be
window.onload = function() {
document.getElementById("title").style.color = "blue";
};
as you cannot change DOM elements before they have loaded.

Likely, since you are loading the js file in the head of your document, the javascript is running before the document is loaded and the title element exists.
There are a couple of ways to deal with it, but the simplest is to move your script declaration to the bottom of your file, instead of the head, so that the script is loaded after the document elements it references.
Vince's answer is another way of ensuring the javascript is run after the elements in question are loaded.

Since the <script> tag is in the head it is getting executed before the body has been rendered, so element "title" does not exist.
There are better ways to do this, but putting the <script> tag just before </body> should work.

As Mentioned by Vince: You should use window.onload so the the code execution will wait till the window is loaded and it makes sure that the DOM is present.
But as an add on it is always a good practice to load javascript in body.
Else your page loading will be stuck till that file is fetched.
In some cases js is getting loaded from some other server and its taking time, DOM will also not render.
And, you can keep the scripts in the head itself by using "defer" atrribute on it. This will serve the same purpose. "Defer" makes sure its loaded after everything is done.
Something like:
<script type="text/javascript" scr="page.js" defer></script>

Related

Is it ever necessary for a <script> tag to go in the <head>?

I have read in the docs of some third party providers (e.g. adsense) that their script must go in the <head>.
For async scripts I'm fairly sure this is untrue since the async flag doesn't guarantee anything about when the script will be executed. But I'm curious about non-async scripts too. Does it makes sense to say that a script tag must go in the <head>?
(This is assuming that there isn't any code in the page that relies upon some script having loaded).
To be clear, my question isn't "is it a good idea", or "what are the performance benefits".
It's more like: "is it technically possible that a script could NOT work, because it isn't in the <head>?"
Thanks!
A <script></script> in the <head> tag will stop the DOM from parsing until the script has loaded. Put scripts here that need to be loaded before the DOM is parsed. Don't put any unnecessary scripts here, as it stops the DOM from parsing. That results in a slow-to-load page.
See: https://stackoverflow.com/a/24070373/47589
The MDN page on the script tag does not place any requirements on the location of a script tag. In fact it seems that the modern trend is now to put scripts at the very end of the body.
A tag can be placed anywhere in the html page, But placing in the tag will slow down the creation of DOM elements in the browser, because browser needs to get all the script tags and move to html elements,
The best practice is to keep the script tag at the bottom of DOM elements, because the visual html elements will be loaded before the script js getting load.
It mainly depends on the functionality of the script and the business logic of the page.

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");
});

Is there a valid reason about putting JS in the head of document?

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.

Where should JS scripts go in an HTML file?

If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go? For instance modifying a <div> or adding some links.
Should this be put in the <body>, interspersed with HTML? Or should it be between the <head> and <body> elements? What order do things happen in - the order they are in the page or does HTML all happen before (non-<head>) JS is run?
If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go?
Just before the closing </body> tag is emerging as the best practice barring a specific requirement for it to be elsewhere (which there can sometimes be). It's the recommendation of the YUI folks, for instance, but it's not just them.
What order do things happen in - the order they are in the page or does HTML all happen before (non-) JS is run?
When a script tag is encountered, unless you use the defer or async attribute (and the browser supports them), all HTML parsing comes to a screeching halt and the script is downloaded and handed to the JavaScript interpreter. When the JavaScript interpreter finishes processing the script, the HTML parser can continue. It has to do this because the JavaScript can insert tokens into the HTML stream via document.write. This is also why you can load a script file and then load a second script file that relies on the first, and know that they'll get loaded in the right order. It's also why you can't access elements that are further down in the HTML stream from a script higher up in it unless you defer your code somehow (window.onload or the "DOM loaded" events many libraries support, such as jQuery's ready or Prototype's dom:loaded).
An upshot of this is that the typical practice of putting script tags in the head actually slows down the apparent load time of the page, unless those script tags need to be there for some reason. Hence the recommendation to put them just before the closing </body> tag.
There's a "gotcha" you have to watch for, though: If you have parts of the page that you want to respond to with JavaScript if the user has it enabled, loading your script at the very end leaves a brief but real race condition lying around: The user can interact with the page while your script is being downloaded. There are a variety of ways of handling that. My favorite is to detect whether JavaScript is enabled with inline script (not a separate file) in the head element and, if so, to put in a document-level handler for things where possible (you can do this with click events, for instance) which basically queues up or disables the click during that very brief period of time. That way, if JavaScript is enabled, you'll avoid the race condition, but if it isn't, any unobtrusive fallback you have in place will work.
The whole HTML file is executed in the order it is written, that means
<html>
<div id="ID"></div>
<script type="text/javascript">
document.getElementById('ID').innerHTML = "HELLO";
</script>
</html>
changes the contents of the div, wherease
<html>
<script type="text/javascript">
document.getElementById('ID').innerHTML = "HELLO";
</script>
<div id="ID"></div>
</html>
does not, because the JS code is executed before the div has loaded.
EDIT: If you want the JS to run after the page has loaded use window.onload or document.body.onload or
<body onload="...">
Alternatively if you're using a JS library such as jQuery, you can use
$(document).ready(function() {
...
});
Put them as functions in its own .js file which you include by <script src> at end of HTML <head> or <body>. If any of them needs to be executed during document load, call it using window.onload or whatever load function the JS library/framework offers, if you are using any.
As to the exact location, putting them in end of <head> allows them to be downloaded before the HTML page is been shown in browser and putting them in end of <body> allows the page to be shown a tad sooner because downloading the scripts will block the page rendering, thus it's a better speed experience.
However, IMO, it's a bit more robust to have the scripts downloaded before the page is rendered whenever you have some page elements which cannot be used without JS. In case of an impatient user this would otherwise lead to unusable elements.
I'd put it in a separate .js file and wrap the code so it is executed after the DOM is loaded. If you use a framework like jQuery or Prototype this should be easy.
For best performance place your JavaScript files at the BOTTOM of the HTML page you are serving.
To ensure that everything is set when you try to use it, execute only after the DOM is ready (there are multiple variations of this, my advice: Use a JavaScript Library).
You can put a script tag in the head, body, between the two, and more. You can put it most places but see this for a more in depth look.

Dynamically Inserting <script> tags into HTML on Page Load

I'm trying to dynamically insert the Tweetmeme button using Javascript. I'm currently using jQuery throughout the site. Here's the script that I'm using. I basically want to cycle through all the blog entries with a class of journal-entry and append the following JavaScript to the end. This Javascript comes straight from tweetmeme.com. This doesn't work for me though and it has something to do with the code between append(). It doesn't like the second set of script tags.
<script type="text/javascript">
$(document).ready(function() {
$('.journal-entry').each(function(index) {
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>');
});
});
</script>
Any help is appreciated.
Thanks.
Don't do this.
Inserting <script> HTML content into the DOM is unreliable: it works subtly differently in different browsers, and jQuery won't protect you from the differences.
In particularly, writing innerHTML never causes a <script> element's content to execute, but subsequently moving the <script> element from where it is to a new parent (which is part of jQuery's append process) may cause the script to execute, but not always (it depends on the browser).
In any case, it'll never work, because looking at button.js, it is calling document.write(). That function only makes sense to call at initial document parsing time; if you call it from an event afterwards, the call will simply replace the entire page content, destroying your existing page. A script that calls document.write() can only be run at document load time, from inside the execution path of a <script> element. You can't include the script in dynamically-created content at all, because it's not designed for it.
(If it makes you feel any better, it's barely designed at all; the button.js script is a badly broken load of old crap, including improper URL-escaping—using escape instead of the correct encodeURIComponent—and missing HTML-escaping. You may be better off well away from these total idiots.)
The closing </script> in the string in your append(...) call is closing the overall <script>
Try splitting it up into two strings. E.g:
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></'+'script>');

Categories