Reputation: 689
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"}]';
Upvotes: 0
Views: 11461
Reputation: 9998
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.
Upvotes: 2
Reputation: 87303
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
Upvotes: 2