How to run a function when the page is loaded?

前端 未结 9 1538
小鲜肉
小鲜肉 2020-11-22 11:02

I want to run a function when the page is loaded, but I don’t want to use it in the tag.

I have a script that runs if I initialise it in th

相关标签:
9条回答
  • 2020-11-22 12:07

    window.onload will work like this:

    function codeAddress() {
    	document.getElementById("test").innerHTML=Date();
    }
    window.onload = codeAddress;
    <!DOCTYPE html>
    <html>
    <head>
    	<title>learning java script</title>
    	<script src="custom.js"></script>
    </head>
    <body>
    	<p id="test"></p>
    	<li>abcd</li>
    </body>
    </html>

    0 讨论(0)
  • 2020-11-22 12:08

    Alternate solution. I prefer this for the brevity and code simplicity.

    (function () {
        alert("I am here");
    })();
    

    This is an anonymous function, where the name is not specified. What happens here is that, the function is defined and executed together. Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.

    0 讨论(0)
  • 2020-11-22 12:09

    As soon as the page load the function will be ran:

    (*your function goes here*)(); 
    

    Alternatively:

    document.onload = functionName();
    window.onload = functionName(); 
    
    0 讨论(0)
提交回复
热议问题