Theo
Theo

Reputation: 33

Is there a way to not load html until JavaScript loads?

I want to make sure that all JavaScript happens before the page is loaded. I am changing some innerhtml, but don't want the original innerhtml to show.

Currently, when my page loads "Books" is displayed for a brief moment, then finally when the script is read, it gets replaced. How do I prevent it from displaying the initial text?

FYI the script exists inside a php file.

<?php
?>
<script>
function changeme(){
var myvar = "test-string-is-long-to-notice-the-changed-text";
var spans = document.getElementsByTagName("span");
for(var i=0;i<spans.length; i++) {
if(spans[i].textContent.trim().toLowerCase()==="books") {       //is this the "Welcome" span?
spans[i].innerHTML = myvar;  //change to new value
break;                                  //hop out of the loop, we're done
}
 }
 }
 window.onload = function() {
 changeme();
 };
</script>

Upvotes: 0

Views: 1537

Answers (2)

Ankush Sharma
Ankush Sharma

Reputation: 677

It is not a good idea to load JS before HTML, because you can not change the HTML elements before loading it using js.

Solution 1: Initially, keep the html tags empty that you do not want to show, because you want to show new data from JS.

Solution 2: Initially, keep the styles for those elements "display: none" and when you add the data using Js in element. Update the style to display: 'block' or any other you want, eg spans[i].style.display = 'block';.

Upvotes: 1

Keith Cronin
Keith Cronin

Reputation: 373

You cant apply JS to a html document that doesnt yet exist. Your html is always loaded first, then your JS is applied. What you could be seeing here is the html is loaded and the JS is taking like what--a second to load and make the change? I recommend figuring out a more efficient way to implement the JS you need. You could just be seeing JS latency. You could use a more efficient implementation plus some CSS to fix it. I could be wrong here but it just doesn't make sense to apply JS to html went the html isnt even there yet.

How would I apply any JS to that if I'm trying to do it before the browser has even parsed and rendered my html?

Also remember that PHP is always "loaded" first, then html, then JS

Upvotes: 0

Related Questions