JavaScript two onload functions

10,598

Solution 1

Yes you can. However, if the first goes wrong, the second won't fire.

Use this to catch errors:

try { //try executing the functions
  function1();
  function2();
}
catch(error) { // If there's an error
  alert(error); // alert the error.
}

It is a good practice to put try and catch when experimenting with javascript.

Edited: Sorry i confused childNodes[] with childNodes.item().

By the way, I tried something like this, and it works just fine:

<head>
<script>

window.onload = function() {
div = document.getElementById("someDiv");
length = div.childNodes.length;
    first();
    second();
}
function first() {
    for(var i=0;i<length;i++)   {
        var set = div.childNodes.item(i);
        set.setAttribute("name", "span " + (i+1));
    }     
}
function second() {
    for(var i=0;i<length;i++)   {
        name = div.childNodes[i].getAttribute("name");
        console.log(name);
    }
}
</script>
</head>
<body>
<div id='someDiv'><span id='span1'></span><span id='span2'></span></div>
</body>

UPDATE: I found the error: Actually there's nothing wrong with your code. It works just fine, however, the last item of boje is empty space, which means, a text node. That's why the error keeps showing up. Change for(i=1; i<broj; i++) with for(i=1; i<broj-1; i++) and everything should be good.

Solution 2

I ran into the same problem. I came across a couple of help but this one was easy to understand and it worked for me:

window.addEventListener("load", func1); window.addEventListener("load", func2);

just like @Quentin You can read more about it here

Solution 3

Can both functions be called with

Yes. If you add event handlers by assigning to DOM properties, then you can only assign a single function to each but that function can call other functions.

However, if you do that and the first function throws an error then the second function won't fire at all. It will also discard the context and arguments, as they won't be passed to the called functions.

You could work around those problems like so:

window.onload=function(){
  try {
    function1.apply(this, arguments);
  } catch (e) { }
  try {
    function2.apply(this, arguments);
  } catch (e) { }
}

or is there a different code I need to use to accomplish this?

You should use addEventListener instead. That avoids the need to fiddle with apply, and protects you from errors being thrown. See the MDN events documentation for more details.

window.addEventListener('load', function1);
window.addEventListener('load', function2);
Share:
10,598
SineLaboreNihil
Author by

SineLaboreNihil

Computer enthusiast, eager to learn.

Updated on June 04, 2022

Comments

  • SineLaboreNihil
    SineLaboreNihil almost 2 years

    I am quite new to JavaScript programming and I'm trying to create some scripts that would save me time in maintaining one of my websites.

    Now I have two functions in the same script that I'm calling from the head of my document and I'm trying to get them both to load at the same time with an onload event handler. I am doing that with window.onload command in my script (I want to make my script as unobtrusive as possible so I'm just calling the script in the header). The problem is that only the first function loads and the second one doesn't. Can both functions be called with:

    window.onload=function(){
    function1();
    function2();
    }
    

    or is there a different code I need to use to accomplish this?

    I would really appreciate it if you could make your explanations as simple as possible as I am very new to JavaScript and programming in general.

    P.S. If more than one function can't be loaded with onload, could you please explain to me why this is the case so I know in the future.

    Ok, I see by the answers that my question probably left too much for assumption so here is the entire code of the functions I am trying to call (this is the script I am calling in the head of my html document):

    I was trying to avoid putting the code here because my variables are written in Serbian language (as I am from Serbia), but I hope that you will still be able to look through it without much confusion.

    In the code below I am calling at the bottom of the script two functions (lista() and ostale()) and the moveover() function is just a helper function called by the lista() function. In essence the first one (lista()) lists through all elements of div "boje" (in English translated to "colors") and depending on the color the user hovers their mouse over, the background image changes. It also adds a few attributes to those image elements that the user is supposed to hover over. The second one (ostale() (Translated to English "others") is supposed to only add attributes to the rest of the color images that are not supposed to do anything if the user hovers over them. But when I open the page in localhost it doesn't show in Firefox's inspect element that any attributes have been added to the images within the div "ostale".

    function lista()
    {
    var boje = document.getElementById('boje');
    var broj = boje.childNodes.length;
    for(i=1; i<broj; i++)
    {
        var stavka = boje.childNodes.item(i);
        stavka.setAttribute("id", i);
        stavka.setAttribute("onmouseover", "moveover(src)");
        stavka.setAttribute("alt", "Boja");
        stavka.setAttribute("class", "boja");
        stavka.hspace="2";
        stavka.height="23";
    }
    }
    
    function moveover(adresaBoje)
    {
    var izvor = adresaBoje;
    var slika = izvor.slice(0, izvor.length-4);
    var pocetak = "url(";
    var ekstenzija = ".jpg)";
    var novaSlika = pocetak.concat(slika, ekstenzija);
    document.getElementById('slika').style.backgroundImage=novaSlika;
    }
    
    function ostalo(){
    var ostaleboje = document.getElementById('ostale');
    var ostalebroj = ostaleboje.childNodes.length;
    for(n=1; n<ostalebroj; n++)
    {
        var ostalestavka = ostaleboje.childNodes.item(n);
        ostalestavka.setAttribute("alt", "Boja");
        ostalestavka.hspace="2";
        ostalestavka.height="23";
    }
    }
    
    window.onload=function(){
    try
    {
    lista();
    ostalo();
    }
    catch(err)
    {
    alert(err);
    }
    }
    

    After I try to load the page it alerts me with an error: "TypeError: stavka.setAttribute is not a function".

    This is the html document I am trying to manipulate:

    <div id="slika" style="background-image: url(images/nova_brilliant/1.jpg)">
    </div>
    
    <div id="tekst">
    
    <h1>Nova Brilliant</h1>
    
    <div id="sadrzaj">
    <p>Pre&#273;ite mi&#353;em preko &#382;eljene boje da biste videli kako izgleda ova kuhinja u toj boji:</p>
    <div id="boje">
    <img src="images/nova_brilliant/1.gif"><img src="images/nova_brilliant/2.gif"><img src="images/nova_brilliant/3.gif">
    </div>
    <p>Ostale dostupne boje:</p>
    <div id="ostale">
    <img src="images/nova_brilliant/4.gif"><img src="images/nova_brilliant/5.gif"><img src="images/nova_brilliant/6.gif">
    </div>
    </div>
    
    </div>