Skip to content Skip to sidebar Skip to footer

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 funct

Solution 1:

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.

<aid="beginner">Beginner Level</a><divid="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

Solution 2:

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

<head>
...
<scripttype="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.

Post a Comment for "Call Javascript Function Before Page Loads"