0

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"}]';
2
  • No, but you can add a script tag immediately after the body. Commented May 2, 2017 at 18:18
  • Is there something missing in my answer for me to add and you accept? Commented May 13, 2017 at 11:55

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

p.s. 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.

2 Comments

Yes, though as the script access element, it will fail since they are not loaded yet
you could 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. It could fix the issue

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.