Where do I put the $(document).ready()? - javascript

I've been trying to add JavaScript to my HTML/CSS, but been running around in circles.
My current set-up is where the html, CSS, and JavaScript files (2 files; my JavaScript code, and jQuery's code) are all separate, but linked to each other via the html page.
So here are my questions:
1) Do I put the link to the jQuery code within the html head? Or within my JavaScript code page?
2) Where does this code go? The html page, or my JavaScript page?
$(document).ready(function(){
//Code here
});
3) Above, by 'code here', they mean JavaScript code, right? Not my html code?
4) I've read about initializing JavaScript code at the bottom of an html page. From what I take though, I don't have to do that with jQuery's .ready function, right?

You should like to your JavaScript files either in the <head> or above the closing </body> tag.
The code can go anywhere really, but I would suggest an external JavaScript page.
Yes
This is correct.

When Javascript code is executing in your browser, all of your included Javascript files and any code you write in-between those "script" tags in the HTML document is going to be executed as though it were all part of one giant file (same namespace). So in some sense, it doesn't matter whether you write your code in the HTML document or whether you write it in an external file that you include - you're free to do either, and it will be executed the same. You can balance maintainability, reusability and convenience (think about what functions you write that you might want to reuse on other pages) and do whichever you feel is best.
To make this concrete - this is one valid way to write your Javascript, if you wanted to write the code inside your HTML file:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('Document Ready!');
});
</script>
</head>
<body>
...
Here's the intro at the jQuery site, for reference:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
Writing your Javascript code at the bottom of the HTML page was/is a technique for getting it to execute as soon as the document is loaded, which is unnecessary when using jQuery's '$(document).ready' (that's what it does - it abstracts the business of getting Javascript functions to execute on page load, and implements it in a cross-browser way).
See: Introducing $(document).ready() for more.

It doesn't really matter where you place your jQuery code. If you place it in the head tag, it'll automatically load everything. If you decide to place it all in an external JavaScript file, you need to link it with a <script type="text/javascript" src="my_file.js"></script> tag.
The 'code here' part is only for JavaScript. What the code is saying is that when the document is ready, run this function. The function can be whatever you like - whatever you put inside the function will run when the document is ready (i.e. when the webpage is called by the browser).
You don't need to insert it at the bottom of the HTML page - you can do it anywhere. People only insert it at the bottom to optimize their loading speed. It's nonessential.

$(document).ready(function(){
//Code here
});
goes in your javascript file. All javascript code that should be executed once the page has loaded goes where the //Code here comment is.
Perhaps a quick jQuery tutorial would be in order?

Or, you can put your script tag in the bottom of your body, and not have to use the $(document).ready() function.

Put in the head. This is the most stable way and it works. Some people may disagree and say it is slower, etc, but I have found this to always work.
Where you put your code is up to you. You can put in your head with a
<script>Code here</script>
or in a separate file and include it with
<script src="reftomyscript.js"></script>
Yes, put your javascript code in this, either in the head or in a separate file.
Yes, and see (1)

Related

What is the priority of execution of javascript?

I have an external JavaScript file linked by blogger. I want to change valuess in it. (css values assigned with JavaScript)
Is it possible to run the same code in head or body with different values assigned with JavaScript?
For example, CSS gives least priority to the external CSS stylesheets and assigns the properties which are given inside the file.
Does JavaScript have any priority system like that?
It is not priority, but execution order. Javascript is not involved in any sort of prioritising or doesn't have anything like specificity in CSS to even have a need for it.
Javascript code is executed in the order it is included in the HTML document irrespective of whether it is inline or external js, although events makes things a bit more complicated, we can schedule code to be run later on certain events like 'load' event of window. So it is easy to make sure your code is run after theirs, but if they are say changing style from onload event handler, then you have to add your code to the same event itself. (Order of event handlers are ensured in DOM3 at least in specification)
But, have you tried !important in CSS, it can override inline styles and comes handy in some scenarios like this. But if you are able to remove the styles using JavaScript well and good.
Javascript code is executed at the point of inclusion.
Html parser
parse tags
finds javascript
(optional)download javascript
stop parsing html
parse js
excecute js
resume parsing html
finds javascript
(optional)download javascript
stop parsing html
parse js
excecute js
resume parsing html
etc
Watch out for things like code that hooks itself to domready events, to only be fired when the document is done loading or other events, then it comes down to in which order they were registered.
There are also things like defer and async, which will make it load/execute in parralel to parsing(details and supporr vary per browser).
But in most scenarios without heavily modified templates in google blogs the sequesce i laid out will happen
JS is executed as soon as it is loaded, so putting your script after theirs (either linking to an external file after, or putting it inline), it will be able to change things in the first script, but it may have executed by then.
You might be able to override parts of it, if their script wait for something before running, like the DOM ready event
if you have tow function with same name, one in head and another one in an external .js file and both of them write a value in <a>, the result will be from the internal one, let's look at an example
<html>
<head>
<script src="myscripts.js"></script>
<script type="text/javascript">
function test(){
document.getElementById("tester").innerHTML="Internal";
}
</script>
</head>
<body onload="test()">
<a id="tester"></a>
</div>
</body>
</html>
-------------------------------------
in myscripts.js
function test(){
document.getElementById("tester").innerHTML="external";
}
-------------------------------------
when the page run it shows:
Internal

Add script to script that contains document.write won't execute

We're using a webprogram that uses ajax and jquery and the like (Netsuite). I want to change something on a page and have tried to use document.ready and window.load to get an external script loaded on the page. I've tried to load the external script in the head and body.. but the contents aren't written. The external file looks for a specific div id and then prepends some code to that. It never works, because the page itself loads dynamically and the div I'm looking for loads when the rest of the page is done. So window.load, etc. never work...
At last I'm in the program itself that loads parts and pieces and am trying to simply write the external script file in there. Now this time the external file has a simple document.write in it, so it's straightforward. In other words, the script is in the middle of html code in the body of the page. (I know this is a terrible way of doing it, but I've got to try something to get this to work....)
According to firebug, it writes the external file where it should be (check!) and firebug shows me the contents of that file (check!), but ... it never 'writes' it onto the page...
The file just contains this:
document.write('<div id="shpblk" style="border:2px solid #ffa500;border-radius:7px;color:#000066;margin:5px;padding:5px;text-align:left;"><img border="0" width="12" height="12" src="/images/icons/store/icon_exclamation2c.gif">Hazardous conditions blahblah... Potential delays and disruptions can be anticipated.</div>');
What am I missing?
Edit: some more clarification is necessary...:
Situation: I have to be able to put a piece of html on the page every now and then that creates a message.
Environment: What I have is a page that loads a header and footer first (which are set up in separate files) and then it takes a second or so to load the rest of the page. From what I understand, this "rest of the page" is written in a certain code, similar to javascript/jquery.
What I CAN do is: edit the files for the header and footer and put javascript in there to make modifications to the rest of the page. I can access some of the files that contain parts and pieces of the "rest of the page", but this is a huge pile of spaghetti.
What I've tried:
Since I want to be flexible with the html that I need to put into the page, I preferably would like to create a piece of javascript or html or whatever on another site and have the "environment" pick up that code. I can do this with javascript or iframe. But since it's a secure area (https), I thought it would be best to use a javascript file instead of an iframe. So....
I created the javascript file and tried it out in a normal environment where I knew for sure it would work.. and it works like a charm. But when I tried this in the before mentioned "environment", I am running against a wall...
The javascript file has document.ready jquery statement in it and it would prepend the html div to an existing div on the page.
This way it would load the page and write the page.. easy as pie.
However.. since the header and footer load first (which includes the external script file), and then the rest of the page, SOMEHOW the div where the script checks for DOES NOT EXIST YET. So I tried window.load instead of document.ready. Same result.
Now, it WOULD appear ONLY when I refresh the page. So there may be a way to have it refresh the page, but I only want this as the absolute last attempt.
So then I tried to see if I could go around this by changing the script so that, instead of using a document.ready it would just do a simple javascript document.write statement.
Then I call the script in the middle of the body of the page (I put it in one of the files that load in the middle of the page). I know this is not something I would do normally, but wanted to try it out anyway. So.... I would have something like this:
<div id="block1">
<div id="block2">stuff here<div>
<script type="text/javascript" src="https://someotherdomain.com/include.js" ></script>
<div id="block3">stuff here<div>
<div id="block4">stuff here<div>
</div>
Now when I run this, I do not get any errors, but nothing is being done with the contents of that js file. In firebug it shows me the contents of that file though.. so I assume it's being read.
But I have no idea why it doesn't run.
Again.. back to 'normal' practices: I've tried window.load, because this would run the statement after the page loads, HOWEVER.. like I said before, I have the feeling it builds the contents of the (middle of the) page through this somehow and my script runs before this; it cannot find the div (block3) where it would prepend to. Whenever I stop running the page at my script, the div it's depending on doesn't exist yet...
I hope this made sense...
Solution
For the external script file to work as expected, OP will need to load it using an asynchronous script tag like this:
<script type="text/javascript" src="include.js" ></script>
Yet, the file contains a document.write() statement, which is generally something to avoid. A better alternative would be remove document.write() from the file and save it as a plain HTML file. This could then be safely loaded using using jQuery:
$("#include1").load("include.html");
( Requires adding a target DIV to the page where the content should load. )
DETAILS
The question doesn't tell us how the external file is included on the page. And without that information it's difficult to understand the problem or provide a solution ... which is probably why this question has gone unanswered.
Yet, let's assume the the script is being injected into the page on the client side using JavaScript or jQuery. And if that's true then it will fail if not done the correct way.
Let's look at some ways we might add the script to the page:
These script tags will all fail because the file contains a document.write statement and the script is loaded asynchronously.
<script type="text/javascript" src="include.js" async ></script>
<script type="text/javascript" src="include.js" defer ></script>
<script type="text/javascript" src="include.js" async defer ></script>
The browser does load the file, but reports:
Failed to execute 'write' on 'Document': It isn't possible to write
into a document from an asynchronously-loaded external script unless
it is explicitly opened.
This jQuery sort of works. It loads the script, but the document.write implicitly calls document.open, which erases the original content of the page. That's probably not what OP wants.
$.getScript('include.js');
This synchronous method works so long as the document.write is executed on load, i.e., is not inside function called later. So this is a possible solution for OP.
<script type="text/javascript" src="include.js" ></script>

Separating jQuery code from HTML

I'm trying to clean up my code so I'm putting all the stuff in my
<style></style>
In a CSS file. And I'm trying to do the same for my jQuery. So I created a Custom.js file. But do things like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Stay in html file or can I move them the Custom.js file? Also, I'm using a jQuery plugin called uscrollbar so I have this piece of code in my html file:
<script>
$(document).ready(function(e) {
$('#scroll_form').uscrollbar();
});
</script>​​​​​​​​​​​​​​​​​
Can I also move that to Custom.js?
A much better question.
It's best to keep links to external scripts in your HTML, it's perfectly fine to have a few <script> tags. Especially ones using a CDN!
You can move your document.ready() function to external JS, where all of your other JS is kept. But sometimes it's easier to include small snippets like that directly in pages where it concerns only that page.
When moving things to separate files, it's important to include them in the right order.
Usually something like Modernizr at the top (<head>), with jQuery near the bottom (just before </body>), followed by your plugins, followed by your custom scripts.
Check out RequireJS, it gives you a super simple way to include javascript files as you need them, rather than stuffing your header / footer full of tons of <script> tags.
Keep your references to Javascript files (local or remote) in your HTML code. Place them at the bottom of the page before the closing body tag if they do not need to be ready until the DOM is ready. For instance, your jQuery reference should almost always be in your 'head' section because any references to jQuery while the HTML loads need to be defined even though functions that aren't called until after document is ready do not need to be defined. Many other supporting files like 'jquery.easing' for instance, can go at the bottom which improves page load times.
You can move the uscrollbar() call to a .js file, but I would recommend putting all of your "ready" commands in one function, and then in your HTML simply call that function on ready. IE:
<script type="text/javascript">
jQuery(document).ready(function() {
fn_LoadFunctionName_Thats_InYour_Custom_js_files();
});
</script>
Don't forget to include type="text/javascript" in your script tags.
If you're using custom js that's more than just one little function call, I'd separate into a new js file and just call that in your <script> tag. Same with css. If you're changing styles with your jquery, then usually I use addClass, removeClass, and toggleClass to modify my styles. That way you don't lose track of your styling from css to js files.
You can certainly move them to Custom.js file. Just make sure you have included the file in your html file as you've included the jQuery library.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="Custom.js"></script>
Just make sure the path for Custom.js is correct. Also, you don't put script tag in the js file. So the Custom.js would be:
$(document).ready(function(e) {
$('#scroll_form').uscrollbar();
});

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

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.

Move jQuery to the end of body tag?

My friend read an article which mentioned that moving all JavaScript files to the end of the closing body tag (</body>), will improve the performance of a web page.
I have moved all JS files to the end except the JQuery and the JS files which are attaching event to an element on page, like below;
$(document).ready(function(){
//submit data
$("#create_video").click(function(){ //... });
});
but he's saying to move the jQuery library file to the end of body tag.
I don't think it is possible, because I am attaching many events to page elements on load using jQuery selectors, and to use jQuery selectors it is must to load jQuery library first.
Is it possible to move JQuery library file to the end of page right before closing body tag (</body>) ??
Thanks
It's standard practice to move all your js includes to the bottom of your page. This is because when a browser loads script, it does not spawn a new thread to do so, so basically the browser will wait until it has loaded the script before it proceeds to the next line.
What this means for your users is that they will see a blank screen. Much better to have them see the full(ish) page as then it doesn't look like it has stalled.
The $(document).ready function says not to run until the DOM has finished being instantiated - so moving it to after body is okay so long as the JQuery library is loaded first. Unconventional and some assumptions may not be correct anymore but okay.
Just take in account that the jQuery JavaScript file must be loaded before any call to the $(...) function.
Use a "Dom Ready Queue" to collect functions to be executed once jQuery is loaded and the DOM is ready.
Example:
<html>
<head>
<script type="text/javascript">
var domReadyQueue = [];
</script>
</head>
<body>
...
<div class="foo"></div>
<script type="text/javascript">
domReadyQueue.push(function($){
$('.foo').doSomething();
})
</script>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function(){
while (domReadyQueue.length) {
domReadyQueue.shift()(jQuery);
}
});
</script>
</body>
</html>
The reason that article asked you to move scripts to the bottom, is to allow other artifacts to get downloaded first. (css & images, which will speed up apparent rendering times)
This is because HTTP 1.1 recommends only downloading 2 items per hostname. And you would definitely want your css file to be one of the first files downloaded, rather than javascript which could make the site appear to render slower (just by the fact that the browser hasn't got the css file yet and isn't sure what it should do with the html)
But if you used google to host your jQuery then that would download in parallel and negates any reason for moving it to the bottom of your pages.
Alternatively, you could set up a second hostname to host static content (such as css/scripts/images).
But google have already done the hard work for you, so it makes sense to use it if it suits. :-)
Q - Why do I often see JavaScript
written/included before the closing
body element in an (x)HTML document?
A - DOM elements can not be accessed
by JavaScript until the browser has
loaded the HTML elements into the DOM.
By placing JavaScript at the end of an
(x)HTML document (before the closing
body element), you will ensure that
the script is called as soon as the
DOM is constructed/loaded and ready
for manipulation. An advantage of this
approach is that JavaScript code is
executed right after the DOM is
constructed and possibly before the
onload event would fire.
JavaScript beginners get tripped up by
this constantly by placing code that
manipulates the DOM in the header
element of an (x)HTML document. This
causes an error because the DOM has
not yet been constructed and thus is
not yet accessible to JavaScript that
traverses/manipulates the DOM.
From JavaScript Execution & Onload Techniques in Web Browsers
Use unobtrusive javascript (adding event listeners to elements instead of onclik ="..." etc).
Put all your .js files at the bottom of the body tag, with the main library (jQuery in this case) placed first, and everything will be fine. You can use a bundler like bundle fu
You will see a big performance boost of loading your page.

Categories

Resources