3

I have this javascript function here for example:

<script type="text/javascript">
  function onLoadFunctions() {
        //some funcitons here...    
  }
</script>

And I wanted to load this function when the page loads using only javascript. Can anyone help me. thanks in advance.

4 Answers 4

6

If I understand what you're asking you probably want to use window.onload.

<script type="text/javascript">
  function onLoadFunctions() {
    //some funcitons here...    
  }
  window.onload = onLoadFunctions;
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

please use addEventListener to do this, not window.onload (also check the "Legacy Internet Explorer and attachEvent" section)
1

You can also use body onload event:

<body onload="onLoadFunctions();" ...>
  ...
</body>

1 Comment

Most likely the use of the onload attribute, rather than delegation with javascript. Twasn't me that dv'd though.
1

The window has an "onload" event which you can listen to with:

window.addEventListener("load",myOnLoadFunction)

Though for more cross-browser compatibility, you may want a function like the below, as older IE versions use .attachEvent instead of .addEventListener

function addEvent(obj,evnt,func)
{
    if(typeof func !== 'function')
    {
        return false;
    }
    if(typeof obj.addEventListener == 'function')
    {
        return obj.addEventListener(evnt.replace(/^on/,''), func, false);
    }
    else if(typeof obj.attachEvent == 'function' || typeof obj.attachEvent == 'object')
    {
        return obj.attachEvent(evnt,func);
    }
}

Then call:

addEvent(window,'onload',myOnLoadFunction);

4 Comments

Why do you have to check if typeof attachEvent is object?
@bfavaretto That's what IE8 & IE7 return (IE8/7 mode in IE9 does, anyway)
Argh! I didn't know that, usually I just check if attachEvent exists.
@bfavaretto Yea, to be fair I could probably change it to if(obj.attachEvent), but this code is from a while ago when I was more inclined to add specificity, and it's always better to be safe than sorry! Although, I'd hope noone's setting window.attachEvent to a number/string lol
0

You have several options to do this:

You can add the event listener in Javascript.

window.addEventListener('load',myOnLoadFunction);

Or if you want you can add the event listener at the html tag.

<body onload="onLoadFunctions();">

Update

You can read more about addEventListener here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.