Javascript and separate script sections [duplicate] - javascript

// Scenario 1
<script>
myFunction(); // This won't work.
</script>
<script>
function myFunction() {
alert("ok");
}
</script>
// Scenario 2
<script>
myFunction(); // This will work.
function myFunction() {
alert("ok");
}
</script>
Why? Thanks for your help!

In JavaScript, scripts are loaded in the order they appear on the page and are blocking. Because you put them in separate script tags, they are loaded separately. The first is loaded and the method executed without it being defined. In the second example, the method definition and the call are loaded at the same time, meaning that the method does exist when it is called.

every script tag the page find, it will execute it.
so the first script, it runs myFunction(), but it's not there, ERROR.
For the second, myFunction is there, so OK.
But pay attention that the following is also error:
<script>
myFunction(); // error
var myFunction = function() {
alert("ok");
}
</script>
when you define myFunction with var, it's now a local variable(here its global scope, so global variable), named myFunction, and only assigned to a function during run-time. So during run-time, you call myFunction() but it is not assigned with a value yet, event don't know whether myFunction is a function or not.
when you do it as following
<script>
myFunction(); // OK
function myFunction() {
alert("ok");
}
</script>
A function named myFunction will be created during something like pre-process, which does some initial work.
and after that is the run-time, which handles myFunction(). So now, when it's called, there is a function with the name of it, no problems.

The entire first script tag is parsed and executed before the second one is considered. As part of parsing a script, function declarations are recognized ahead of time, which is why the second one works while the first one doesn't.
JavaScript: The Definitive Guide
JavaScript statements that appear between and tags are executed in order of appearance; when more than one script appears in a file, the scripts are executed in the order in which they appear. If a script calls document.write( ), any text passed to that method is inserted into the document immediately after the closing tag and is parsed by the HTML parser when the script finishes running. The same rules apply to scripts included from separate files with the src attribute.

Javascript is client side scipting language. When web page loads browser checks for all syntex and function available in the page.
If you are defining a function within one <script> tag and calling from other <script> tag then browser will only check within first <script> tag.
If you want to call a function from any script tag then put the function in js file and use it in html page.

rajesh kakawat's answer seems to agree with what I observed but I haven't seen this issue addressed directly in Flanagan's book, "JavaScript: The Definitive Guide" or elsewhere.
js is read and 'compiled' together (with script tags above in the page's html) and executed script tag by script tag - one script tag at a time - consecutively down the page using all of the definitions, etc. from all of the script tags above (but not from script tags below in the page's html).
This is what appears to be happening:
read current script tag'w js chunk (the entire script tag)
combine and 'compile/interpret' with all previously processed script tags above current script tag
execute all js under current script tag
process any resultant html output by current script tag (document.write)
parse html moving down to next script tag below then go back to step 1 if another script tag is hit below.
This means that if a function is defined in a script tag below (hasn't been processed yet) and called in the current script tag then a "'function x' undefined" error will occur because the js interpreter doesn't know about it yet. However within a given script tag a function can be defined below the call in the listing and work the same as if it had been defined above in the listing.

Related

Defer execution of <Script> tag until after jQuery .load completes

I'm trying to 'include' some generated HTML code on my page with jQuery load (injecting it into #loadhead div):
<script>
$("#loadhead").load("head.php");
</script>
<script defer>
... rest of the code
</script>
I want the second part of the script to load only after head.php is done loading. I tried to enforce execution of the second script tag with defer, but it deson't seem to work - still, once in a while, head.php doesn't manage to load before the rest of the code. What can I do to ensure it is always loaded completely? It generates some JavaScript values that are used by the 'defer' script.
Two options for you:
1. Use a function you call from load's callback
Put your second script's code in a function, so it's loaded but not run, and then call that function from load's success callback.
Example:
<script>
$("#loadhead").load("head.php", otherStuff);
function otherStuff() {
// ...
}
</script>
(I didn't see any reason they should be in separate script tags, so they aren't.)
I'd probably put that all in a .js file and link it rather than having script embedded in the HTML inline.
2. Load the script when load is done
Don't include the second script tag at all; load the script later in the load success callback, either using $.getScript or appending a script element.
Example:
<script>
$("#loadhead").load("head.php", function() {
$.getScript("otherstuff.js");
});
</script>
(I didn't see any reason they should be in separate script tags, so they aren't.)
I'd very much go with Option #1, to avoid unnecessary delays.

why I couldn't call js function in another part of a html page?

Why does the first JavaScript snippet work, and not the second?:
<script>
commenta();
function commenta(){
alert('test');
}
</script>
<script>
commenta();
</script>
<script>
function commenta(){
alert('test');
}
</script>
As said in the comments, it works because of Hoisting. Javascript engine will move all the declarations to the top of function/global definition.
But second example is throwing an error because Hoisting won't work across <script> tags.
Try swapping the order of script tag, it should work.
fiddle: Your code (Before swap)
fiddle: After swap
commenta();
function commenta()
{
alert('test');
}
In this example, the browser will move all function declarations to the top of the script block and then execute the call.
In the other example, the browser does not yet know how to execute commenta since it hasn't parsed that part of the DOM yet.
You are calling the function before the function is registered, as the 2 tags are registered separately under different tags, where the when the statements are included together under one script tag they are registers as a whole. It's best practice to only call a function after it's been declared.

Which event I have to use in jquery to get called before my page elements load?

I want to use boomrang framework in Jquery to get the bandwidth of the user's network which has to be displayed on the screen as "connection : fair/poor/good".
With on ready,on load, etc.., javascript function will be called only after the elements are ready to be accessed. But, I want the boomrang call to be called quite before that. Please tell me which event I have to use so that function call can happen before the elements of the page loads. Thanks in advance.<>
Note: I have tried by putting script tag at the top of the head tag. But still page elements are getting evaluated first (along with their el expressions).
If you want your function to be called before DOM creation then you dont need to call your function in any onload or on(document).ready, what you have to do is just call your function inside the script tag
For example (Script on the top of the page)
<script>
function abc()
{
// function desc
}
abc(); //Will be called as soon as the url is opened
$(document).ready(function()
{
abc(); // will be called when the DOM is ready
});
</script>
Use bw plugin from boomrang freamework
http://yahoo.github.io/boomerang/doc/howtos/howto-3.html

In javascript, only the function call before it's defined in the same script tag works

// Scenario 1
<script>
myFunction(); // This won't work.
</script>
<script>
function myFunction() {
alert("ok");
}
</script>
// Scenario 2
<script>
myFunction(); // This will work.
function myFunction() {
alert("ok");
}
</script>
Why? Thanks for your help!
In JavaScript, scripts are loaded in the order they appear on the page and are blocking. Because you put them in separate script tags, they are loaded separately. The first is loaded and the method executed without it being defined. In the second example, the method definition and the call are loaded at the same time, meaning that the method does exist when it is called.
every script tag the page find, it will execute it.
so the first script, it runs myFunction(), but it's not there, ERROR.
For the second, myFunction is there, so OK.
But pay attention that the following is also error:
<script>
myFunction(); // error
var myFunction = function() {
alert("ok");
}
</script>
when you define myFunction with var, it's now a local variable(here its global scope, so global variable), named myFunction, and only assigned to a function during run-time. So during run-time, you call myFunction() but it is not assigned with a value yet, event don't know whether myFunction is a function or not.
when you do it as following
<script>
myFunction(); // OK
function myFunction() {
alert("ok");
}
</script>
A function named myFunction will be created during something like pre-process, which does some initial work.
and after that is the run-time, which handles myFunction(). So now, when it's called, there is a function with the name of it, no problems.
The entire first script tag is parsed and executed before the second one is considered. As part of parsing a script, function declarations are recognized ahead of time, which is why the second one works while the first one doesn't.
JavaScript: The Definitive Guide
JavaScript statements that appear between and tags are executed in order of appearance; when more than one script appears in a file, the scripts are executed in the order in which they appear. If a script calls document.write( ), any text passed to that method is inserted into the document immediately after the closing tag and is parsed by the HTML parser when the script finishes running. The same rules apply to scripts included from separate files with the src attribute.
Javascript is client side scipting language. When web page loads browser checks for all syntex and function available in the page.
If you are defining a function within one <script> tag and calling from other <script> tag then browser will only check within first <script> tag.
If you want to call a function from any script tag then put the function in js file and use it in html page.
rajesh kakawat's answer seems to agree with what I observed but I haven't seen this issue addressed directly in Flanagan's book, "JavaScript: The Definitive Guide" or elsewhere.
js is read and 'compiled' together (with script tags above in the page's html) and executed script tag by script tag - one script tag at a time - consecutively down the page using all of the definitions, etc. from all of the script tags above (but not from script tags below in the page's html).
This is what appears to be happening:
read current script tag'w js chunk (the entire script tag)
combine and 'compile/interpret' with all previously processed script tags above current script tag
execute all js under current script tag
process any resultant html output by current script tag (document.write)
parse html moving down to next script tag below then go back to step 1 if another script tag is hit below.
This means that if a function is defined in a script tag below (hasn't been processed yet) and called in the current script tag then a "'function x' undefined" error will occur because the js interpreter doesn't know about it yet. However within a given script tag a function can be defined below the call in the listing and work the same as if it had been defined above in the listing.

Can I put a script at the bottom of a web page, but call it from the top?

Could this cause potential problems:
<HTML>
<BODY>
...
<INPUT name="xyz" onchange="myFunction();">
...
<SCRIPT>
function myFunction()
{
...
}
</SCRIPT>
</BODY>
</HTML>
What happens if the page loads slowly and the form renders before the script portion at the bottom is loaded? Will a JavaScript error occur if the user enters some text into the INPUT box?
You need to load the script before you can call it. Why don't you change it to something like this:
<input name="xyz" id="myInput">
...
<script>
function myFunction
{
...
}
window.onload = function() {
var myInput = document.getElementById('myInput');
myInput.onchange = myFunction;
}
</script>
This approach allows you to separate your markup and scripting and have all of your js in one place.
JavaScript development has changed over the years.
Not only is your original question being debated, but to go back to the theme of your original question, so is your methodology itself.
I highly recommend reading this short bit on some JavaScript best practices:
http://www.catswhocode.com/blog/best-practices-for-modern-javascript-development.
It works, though it may be a problem if you loaded more HTML and it took longer for the browser to parse your JavaScript at the end. In that case, your function won't be defined and you will get...
myFunction() is not defined
Note you need to add open and closing parenthesis (( & )) after myFunction.
Whilst functions declarations are hoisted, they are only hoisted in their containing script block.
Also, you should really use lowercase tags, it isn't 1998 anymore :) And a doctype also helps, and finally, you should try and remove your event handlers from inline attributes.
The script needs to be defined in the DOM prior to it being executed. If script is at the bottom it needs to be loaded prior to use.

Categories