Strange behaviour with two *.js which has window.onload directives

Hi fellows, how are you? I’m stuck here with this. Perhaps you will
suggest me to learn some more abstracted JS framework but by now I’m
trying to learn the deeps of raw JS.
I have 2 files, one is app/javascript/file_1.js and the other is
app/javascript/namespace/file_2.js . Both of them do:

window.onload = function() {
// something
}

Both gets required by the application.js manifest, I’ve tested it
putting an alert(‘Eyaa’) on both files, alert gets executed twice, so
working, good.
Here comes the issue: just one window.onload get listened, the other
not. The one listened is the first required(first file required). I
wonder why does this happen? One file is for one view, and the other
file is for another view, I want to have the code splitted, for order.
Don’t have a clue. Can you help me?

Okay, I’ve found why!!! But this arise another question.
I’ve tested this: erased one of the files, in the other I’ve added a
window.onload below the first window.onload and a strange thing
happened: the last window.onload gets executed, but not the first.
So this takes me to the conclusion: I can’t “monkeypatch”
window.onload, can be called just once, not only once in one *.js, even
in the whole JS filesystem. Why works this way?

Been doing some little more stuff. If I put the code of both *.js on the
corresponding views(inside ) works like a charm. So
why?

On Sat, Jun 21, 2014 at 5:45 PM, Damián M. González
[email protected] wrote:

Okay, I’ve found why!!! But this arise another question.
I’ve tested this: erased one of the files, in the other I’ve added a
window.onload below the first window.onload and a strange thing
happened: the last window.onload gets executed.
So this takes me to the conclusion: I can’t “monkeypatch”
window.onload, can be called just once, not only once in one JS, even in
the whole JS filesystem. Why works this way?

If you open a JS console and enter:

x = ‘foo’
x = ‘bar’
x

what value does x have? Hint: it’s not ‘foobar’ :slight_smile:

Now try the same thing with window.onload.

If you want to avoid using libraries like jQuery for now, look at native
JS methods like e.g. window.addEventListener()

HTH,

Hassan S. ------------------------ [email protected]

twitter: @hassan

Yes, I’ve realized that onload is an attribute of window, so if I do
window.onload = something twice I’m overwriting the value of the
attribute. Thanks.