Jump to content

Avoid rendering of initial div


sorenchr

Recommended Posts

Hi, this thread is a bit ajax-related, but should be readable to the javascript-only enthusiast. I'll start off by showing the source code for two pages, page1.html and page2.html:

 

Page1.html:

<script type="text/javascript">

//Detect hash
if(window.location.hash.length > 0) {
  var hash = window.location.hash;
  //Strip hash of # and parse through getContent
  getContent(hash.replace("#", ""));
}

function getContent(URL) {
  var xmlhttp;
  xmlhttp=new XMLHttpRequest();

  xmlhttp.onreadystatechange=function() {
    if(xmlhttp.readyState==4 && xmlhttp.status==200) {
      var newContent = xmlhttp.responseText;
      var newElement = document.createElement("div");
      newElement.innerHTML = newContent;

      for (var i = 0; i < newElement.childNodes.length; i++) {
        if(newElement.childNodes[i].id == "content") {
          document.getElementById("content").innerHTML = newElement.childNodes[i].innerHTML;
          break;
        }
      }

    }
  }

  xmlhttp.open("GET", URL, true);
  xmlhttp.send(null);
}

</script>
<body>
<div id="content">Page1 div still here!</div>
</body>

 

Page2.html:

<div id="block1">aaa</div>
<div id="content">bbb</div>
<div id="block2">ccc</div>

 

What basically happens, is that Page1.html requests some new content via ajax from a given URL(derived from the window.location.hash). It then selects a specific portion of that requested content do be displayed in the "content" div(namely the "content" div from page2.html.

 

God, I hope this is readable...

 

Anyway, the script works fine, however page1.html renders the initial div content, "Page1 div still here!" and leaves it there until the ajax-request is through, which results in a quick flash of "Page1 div still here!"(0.1 ms) and then the requested content replaces it.

 

Is there any way I can prevent this?

 

Thanks for your time!

Link to comment
https://forums.phpfreaks.com/topic/178071-avoid-rendering-of-initial-div/
Share on other sites

In that case, you can add:

 

document.getElementById("content").css.display = "none" at the very start of your javascript to hide the div as soon as it can, and then add document.getElementById("content").css.display = "block" right after the content is loaded to show it when it's ready.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.