I have a ti开发者_高级运维tle bar on my web page that sets a message to the user. The title is created dynamically by JavaScript. I would like the content to appear without any visible delay in the page where the UL doesn't contain any LI, and then suddenly they're populated. Is this possible? What JavaScript DOM loading event do I want to use?
The reason you typically have to wait for the document to load (document.ready
these days) is so that the element exists within the DOM so you can select it. If the element you need to modify already exists within the page, you won't need to wait.
The following example won't work
<script>
var foo = document.getElementById('foo');
...do more stuff with foo...
</script>
<div id="foo"></div>
It wont work because the DOM hasn't loaded div#foo
when the script is executed
The following example will work
<div id="foo"></div>
<script>
var foo = document.getElementById('foo');
...do more stuff with foo...
</script>
It works because div#foo
has already been parsed and the element exists.
There's no particular event that you can listen for with JavaScript for cross-browser node creation. But if your script can be placed after the element has been created, you can work with the element instantaneously.
Generally speaking, in Javascript when you want something to appear smoothly, even though building that something is not smooth, what you do is just hide everything until it is ready.
In other words, if you do:
<ul style="display:none"></ul>
then add some Javascript to add the LIs, then show the UL, you should have the effect you want. The JS to add the LIs can go anywhere after the UL, or anywhere before if you put the logic inside an onReady or onLoad handler.
Here's a quick jQuery example:
<ul id="myList" style="display:none"></ul>
<script>
for (var i = 0; i < 5; i++) {
$("#myList").append("<li>" + i + "</li>");
}
$("#myList").show();
</script>
ie. start the UL hidden, add stuff to it, then show it. Hope that helps.
精彩评论