difference between the window.onload and (function() {})(); - javascript

I'm actually seeing this script in javascript (function() { //some code; })(); than using the window.onload what is the difference of the two? and which of the two is prefer to use?

An Immediately Invoked Function Expression is invoked immediately.
A function assigned to onload is invoked when the load event fires (which is when the page and its dependencies have finished loading).

The window.onload() waits for the window/page to be loaded before running it.
(function() {})(); run instantly if inserted into head section, before the DOM is constructed.

Related

In what order will these functions get executed?

I am rewriting a project of mine and this time I decided to use self invoking functions to save a bit of code, but I became very uncertain if this would even work since I don't want the self invoking functions to be run before page has loaded + the init function has been run.
The expected execution order I want is this:
init: function() {
//some code gets executed here
createCalendar(2015);
}
addEventListnrs: (function() {
//event listeners gets added here on elements that gets created
//in the createCalendar function
})()
createCalendar: function(year) {
//creates elements that the addEventListnrs uses
}
window.onload = init;
Question is, is this what I'm going to get or will the addEventListnrs function invoke itself before init gets run?
Assuming your labels are valid code (i.e. you've left some code out)
The IIFE labelled addEventListnrs invokes itself as soon as the interpreter reaches it
...some time passes as the page loads... ...and it finishes loading
The load event is sent to window
init is invoked by the listener
createCalendar is invoked by init

Could someone please help me to understand the following block of code?

I am a little confused by the following block of code. I will comment next to each line what I think it means. If someone could help me clarify any misunderstandings I have or confirm that I am in fact interpreting it correctly, I would very much appreciate that.
Here is this code in context: http://jsfiddle.net/MddHtt13/EMBZr/1/
if(!window.onload) { // If the window is not loaded then...
window.onload = function() { //Assign an anonymous function to the onload event
onLoad(); //Which, upon execution of the onload event execute the onLoad function
};
}
else { //This is probably the most confusing part
var oldWindowLoadFunction = window.onload; //Else if the window is loaded, assign the onload event to the variable oldWindowLoadFunction
window.onload = function() { //Then upon completion of the onload event, assign an anonymous function
oldWindowLoadFunction(); //which then re-executes the onload event
onLoad(); //and then executes the onLoad function
};
}
The first thing I don't understand is the exclamation point next to window.onload
if(!window.onload)
Why would I need to specify if the window is not yet loaded? Wouldn't I only want to attach the onLoad() function to the onload event so that upon completion it fires? Say with something like:
window.onload = onLoad();
Why the extra steps? Why the if/else statement?
Secondly, why in the second half of the code block do I need to reload the page only to reattach the onLoad() function again? That sort of brings me back to what I just asked. Why does it have to be more complicated that simply writing:
window.onload = onLoad();
Ofcourse when I change the code to be a simple statement, like the one above, it doesn't actually work. However, I still don't completely understand the necessity of each part of the code block in question.
If someone could walk me through this in detail it would be extremely helpful.
Edit:
Thanks to the help of the folks below I replaced all of this code with one simple statement:
window.addEventListener('load', onLoad);
The ! is a boolean inversion: if not window.onload is null or undefined, or in plainer English, if the variable named onload in the object named window is not null or undefined.
The logic basically says, if there is no onload function install mine. If there is an onload function install a new wrapper function which calls the existing function and then calls mine.
None of the code "reloads" the page. You are confusing the assignment of the onload handler with loading the page.
What the function is doing is adding onload functionality to a window object which may already have onload functionality by chaining added function to the original, but only if that's necessary.
In today's world, it's all redundant, since you can just add an event listener to a list of functions to be executed for the onload event.
if (!window.onload)
This is checking to see if window.onload is not null or undefined. If window.onload is already defined elsewhere then you might not want to replace it with your onLoad() function.
Your block of code basically checks to see if window.onload is defined elsewhere. If it isn't, assign onLoad() to window.onload. If it does, execute the existing window.onload and then call your onLoad() function as well.

What's the correct way to call JavaScript Function?

In the following code, the function writeMessage is called without parenthesis. However it works fine but Is it a correct way of function calling in javaScript or its better to use parenthesis along with writeMessage().
window.onload = writeMessage;
function writeMessage()
{
document.write("Hello World");
}
window.onload = writeMessage; is not a call - it's an assignment. You assign the writeMessage function as the onload field of the window object. The actual call is performed (internally) as window.onload() which is equivalent to writeMessage() in your case.
In the following code, the function writeMessage is called without parenthesis.
Actually, it isn't. The code
window.onload = writeMessage;
does not call the function. It assigns the function to the onload property of window. Part of the process of loading the page in browsers is to fire the function assigned to that property (if any) once the loading process is complete.
If you wrote
window.onload = writeMessage();
what you'd be doing is calling writeMessage and assigning the result of the call to window.onload, just like x = foo();.
Note that the code you've actually quoted, which executes a document.write when the page loads, will wipe out the page that just loaded and replace it with the text "Hello world", because when you call document.write after the page load is complete, it implies document.open, which clears the page. (Try it here; source code here.) In modern web pages and apps, you almost never use document.write, but in the rare cases where you do, it must be in code that runs as the page is being loaded (e.g., not later).
the () is used to EXECUTE the function
when you write
window.onload = writeMessage;
you actually set a delegate ( pointer to a function to be executed) for which - when the onload event will occour.
That's correct already.
You don't need parenthesis because you're just storing the function in window.onload, not calling it yourself.

How to set JS events at the right time

In the rails.js that came with my rails (3.0.x, still with prototype), I see the following structure:
(function() {
// ...
document.on("click", ...
})();
What exactly is accomplished with the wrapping of the whole code in the anonymous function? Is this a valid way to delay the code until the dom has loaded or only the document object?
In my project, I currently have a lot of setup code inside a Event.observe(document, 'dom:loaded', function() { ... } block. I was wondering, if I should adopt the pattern above when I refactor my code.
You have stumbled across the module pattern. It is useful because variables inside the immediately invoked function are local and don't pollute the global namespace.
(function(){
var something = 17;
//can use something inside here
}());
//but not here anymore
Not ethat there is no difference in timeing since the function is immediately invoked (in the final () bit)
The self-invoking anonymous function will trigger what is inside immediately, which has nothing to do with delaying the code.
To make the code block inside be executed after the DOM is ready, you have to have DOMready listener. I guess the code you mentioned Event.observe(document, 'dom:loaded', function() { ... } is the one.

jQuery document.ready vs self calling anonymous function

What is the difference between these two.
$(document).ready(function(){ ... });
(function(){ ... })();
Are these both functions called at the same time?
I know, document.ready will be triggered when the entire HTML page is rendered by the browser but what about 2nd function (self calling anonymous function). Does it wait for browser to complete rendering the page or it is called whenever it is encountered?
$(document).ready(function(){ ... }); or short $(function(){...});
This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.
(function(){ ... })();
That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act on DOM elements here.
(function(){...})(); will be executed as soon as it is encountered in the Javascript.
$(document).ready() will be executed once the document is loaded. $(function(){...}); is a shortcut for $(document).ready() and does the exact same thing.
The following code will be executed when the DOM (Document object model) is ready for JavaScript code to execute.
$(document).ready(function(){
// Write code here
});
The short hand for the above code is:
$(function(){
// write code here
});
The code shown below is a self-invoking anonymous JavaScript function, and will be executed as soon as
browser interprets it:
(function(){
//write code here
})(); // It is the parenthesis here that call the function.
The jQuery self-invoking function shown below, passes the global jQuery object as an argument
to function($). This enables $ to be used locally within the self-invoking function without needing
to traverse the global scope for a definition. jQuery is not the only library that makes use of $, so this
reduces potential naming conflicts.
(function($){
//some code
})(jQuery);
$(document).ready(function() { ... }); simply binds that function to the ready event of the document, so, as you said, when the document loads, the event triggers.
(function($) { ... })(jQuery); is actually a construct of Javascript, and all that piece of code does is pass the jQuery object into function($) as a parameter and runs the function, so inside that function, $ always refers to the jQuery object. This can help resolve namespacing conflicts, etc.
So #1 is executed when the document is loaded, while #2 is run immediately, with the jQuery object named $ as shorthand.
document.ready run after DOM is "constructed". Self-invoking functions runs instantly - if inserted into <head>, before DOM is constructed.

Categories