Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute JS on page load without using jQuery

So I know that if you use jQuery you can use $(document).load(function(){}); so that any code you write into the function gets executed after the whole page has loaded, but is there a way of doing something similar if you don't use jQuery and just use JS?

For example...

<html>
    <head>
        <script type="text/javascript">
            var box = document.getElementById('box');
            alert(box);
        </script>
    </head>
    <body>
        <div id="box" style="width:200px; height:200px; background-color:#999; 
margin:20px;"></div>
    </body>
</html>  

If I use this method the alert just says null. So is there a way of making the js code run once the page has loaded?

like image 882
user1563944 Avatar asked May 25 '13 20:05

user1563944


People also ask

Can we use JavaScript without jQuery?

Don't get me wrong - jQuery is still a wonderful library and most often than not you will be better off using it. However, for smaller things like simple pages with limited JS interactions, browser extensions and mobile sites, you can use vanilla JS.

How do I run a script on page load?

You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document.

Does JavaScript run on page load?

onload runs after page load and all javascript is available, so the codeAddress() function can be declared anywhere within the page or linked js files. It doesn't have to come before unless it were called during the page load itself. @Jared Yes it does.


2 Answers

I use:

<script type="text/javascript">
    window.onload = function(){
        //do stuff here
    };
</script>

This way you don't have to use any onload tags in your html.

like image 153
Nile Avatar answered Oct 14 '22 08:10

Nile


The easiest way is to simply put your script at the end of the document, typically just before the closing body tag:

<html>
<head>

</head>
<body>
<div id="box" style="width:200px; height:200px; background-color:#999; margin:20px;"></div>
<script type="text/javascript">
    var box = document.getElementById('box');
    alert(box);
</script>
</body>

</html>
like image 39
79IT Avatar answered Oct 14 '22 08:10

79IT