window.onload function not running - javascript

I'm facing a weird issue. The console.log() outside the onload function works, but the console.log() inside doesn't work... Would it mean that my page never fully loads ? I had a look at the developer tools of Chrome and it shows me that the page is loaded, so I don't really understand... (here is a screen of the devtool)
Here is my code:
console.log("hello1");
window.onload = function()
{
console.log("hello2");
};
(I'm using this in a WordPress website, but I don't think it changes anything)
Thanks in advance,
ArbreMojo.

Some other code is probably assigning another function value to the window.onload method, so it basically overrides your assignment.
Instead of window.onload = function you can do:
window.addEventListener('load', function() {
console.log('loaded')
})
which allows attaching an arbitrary number of handlers for that event. This ensures nothing can override your callback function.
See: EventTarget.addEventListener for more info.

Related

Declared function seen as undefined by IE 11

I am having some problems with function declarations in IE. It appears, even if I link the function directly to the window object. I tried switching with document in stead of window, but with no success.
Here is the basic code that I am trying to use:
window.addEventListener('load', function () {
function initChart (id) {...}
//linking to window object
window.initChart = initChart;
});
As I said, I even tried to link it directly: window.initchart(id){...}. More that that, I even included the js file I declared the function inside the body(due to a rumor that says that IE doesn't see function declared in head section)
After that, inside script tags i call initChart() with a valid id and I get this error inside the IE console: 'initChart' is undefined.
<script>
initChart('chart');
</script>
The strange thing is that in Chrome, Firefox and Opera has no such problem. Any ideeas?
PS: If this is a duplicate, I did not found the question that covers this.
You also need to do initChart('chart'); inside of the window load event handler (this one or a later added one). Or you can do that in another event handler that you know for sure happens after this window load event handler.
As your code is processed by the browser, it knows to do something on the window load event, which is to set your window.initChart.
But then later on you are using it right away, without the event of window load happening yet.
If it doesn't happen in Chrome, I am wondering if everything is loaded, but even so, I'd think your window.initChart is set in the next event cycle. (let me try to do some experiments -- you are not doing any of these in the debugger but all inside an HTML file?). But it really shouldn't be ok in Chrome, because the load event handler doesn't occur before your <script> tag is parsed and executed, which does initChart('chart'); already.
But in any event, it is best to follow the event sequence: if you set window.initChart on window load event handler, then also only call window.initChart() in the same and later added event handler, or in an event handler that happens afterwards.
You can see in the following HERE 02 happens before HERE 01:
window.addEventListener('load', function() {
console.log("HERE 01");
});
console.log("HERE 02");
I am running the following in Chrome and I did get an error as expected:
window.addEventListener('load', function() {
function foo() {
console.log("HERE 01");
}
window.foo = foo;
});
foo();
But this one worked as expected:
window.addEventListener('load', function() {
function foo() {
console.log("HERE 01");
}
window.foo = foo;
});
window.addEventListener('load', function() {
foo();
});
The problem apparently was not the linkage between the function and the window object. In my load event I had some ES6 string interpolation(something like this: console.log(`#${id}`)) and IE falls short on this. He doesn't know what to do with it. So as a consequence, my window.initChart() was not even compiled. After I commented the code in matter, my initChart function was working fine. Thanks for help tho, #nopole!

jQuery.proxy() Function not being called in Chrome

I am facing an issue where a jQuery function is not being called even though the proxy has successfully loaded (from what I can tell). The call we are making works fine on first load, but when we try to load this script in via AJAX it calls the required $.proxy() to the Initialise function, but then doesn't actually call that function.
The dynamic loaded in code is:
<script language="JavaScript"><!--
var ctrl = new VideoControl({"Id":"bc1093c8290a4037846c2052695a7d3a"}, "...");
//-->
</script>
And the javascript to create the object is:
function VideoControl(controlIds, videoMarkUp) {
this.controlIds = controlIds;
this.videoMarkUp = videoMarkUp;
var thisControl = this;
$(function () { $.proxy(thisControl.Initialise(), thisControl); });
}
VideoControl.prototype.Initialise = function () {
// do stuff
}
So the main function is called, but the Initialise() is not called when this is loaded in via AJAX controls in Chrome or IE...this does however work in firefox.
There is a stackoverflow answer which explains why $function is not being called but how do I get it to a point it will call (similar to how firefox deals with it)
Is anyone aware of something that firefox does differently when working with jQuery vs the other browsers?
There are no errors showing on the chrome developer tools, is there anywhere else that could be looked at in order to diagnose this?
Thank you in advance.
So the main function is called, but the Initialise() is not called
when this is loaded in via AJAX
$(function() {}) is alias for .ready() ; handlers for .ready() should be called at most once . AJAX appear to occur after document is loaded ? , where .ready() has previously called , $.isReady set to true preventing handlers within subsequent .ready() or $(function(){}) from being called.
Try removing $(function() {}) wrapper surrounding
function VideoControl(controlIds, videoMarkUp) {
this.controlIds = controlIds;
this.videoMarkUp = videoMarkUp;
var thisControl = this;
$.proxy(thisControl.Initialise, thisControl);
}
use
$(document).ready(VideoControl)
Though , not certain why $.proxy is used here ? , as the context of thisControl.Initialise not appear to be changed to a different context : this ?
Note also that js at Question thisControl.Initialise() called function; where function should be referenced jQuery.proxy( function, context [, additionalArguments ] )

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.

onclick firing on page load, need to call function with parameters

Sorry if this may be deemed a slight duplicate, however I couldn't find an answer that helped me understand why myFunc() is firing on page load and not when I click el1 or el2. How can I make the following code behave as expected?
function myFunc(param){
//yadayada
}
el1.onclick = myFunc('string1');
el2.onclick = myFunc('string2');
Thanks.
document.getElementById('el1').onclick = function() { myFunc('string1'); };
document.getElementById('el2').onclick = function() { myFunc('string2'); };
You need to get the elements on the page first and then assign a function to them, otherwise the parser will execute them onload because it thinks that myFunc() is returning a value to be assigned to onclick as opposed to the actual function myFunc().

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.

Categories