简体   繁体   中英

Call javascript function before page loads

I'm calling a function load() on body's onload event. Sometimes this function work and sometime it doesn't. As per my understanding, until the body is completely loaded, this function will not get called. Is there any way I can call this function before the page get loaded ?

Here is home.html:

<script src="js/custom.js"></script>
<script src="js/props.json"></script>
<body onload="load()">

<a id="beginner">Beginner Level</a>
        <div id="beginner-sub" class="well">
            <!-- append content here -->
        </div>

</body>

custom.js load function:

function load() {
    var mydata = JSON.parse(beginner);  
    var rows = "";
    for(var x=0; x < mydata.length; x++)
    {
    rows += '<a href="'+mydata[x].url+'">'+mydata[x].title+'<i class="fa fa-hand-o-right pull-left" aria-hidden="true"></i></a><hr>';
    }
    $("#beginner-sub").append(rows);
    $("#beginner-sub hr:last-child").remove()
}

And this is my props.js

beginner = '[{"title" : "Simple Program", "url" : "simple.html"}, {"title" : "Check Palindrome", "url" : "palindrome.html"}]';

If you move the code inside the script tag it is executed immediately when found:

<head>
...
<script type="text/javascript">
     alert("executed now"); 
</script>
</head>

This is for answering to your question about executing code before page loads. But if you access some element, you have to ensure that this code is executed after the element has been loaded.

ps you could also split up your code, parsing the JSON before the page loads, saving results inside a variable, and then append elements after the page has been loaded.

No, can't (or shouldn't) force the body onload event to fire, but you can add a script tag immediately after the element in question.

<a id="beginner">Beginner Level</a>
<div id="beginner-sub" class="well">
     <!-- append content here -->
</div>
<script>load();</script>

Do note though, that any other functions the load() depends on must have been loaded or else it will fail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM