thirdage
thirdage

Reputation: 225

How to link multiple javascript files where both files have an onload event?

I have two files file1 and file2 and am using window.onload in both files. when am linking to these files in html

<script type="text/javascript" src="file1.js">
<script type="text/javascript" src="file2.js">

the second file is running (its onload event is triggered) while the first file is dead. what can I do to make both files run? Is there any other way than making a huge file (file1's content + file2's content)?

Upvotes: 2

Views: 84

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382454

Use addEventListener :

window.addEventListener('load', function(){

Callbacks are all called, adding one doesn't remove the ones you added before.

If you want to be compatible with IE8, use a shim like this :

function addOnLoad(callback) {
    if (window.addEventListener) window.addEventListener('load', callback)
    else (window.attachEvent('onload', callback);
}

addOnLoad(function(){

Upvotes: 10

Related Questions