开发者

Early appendChild hell in top 3 browsers

I'm trying to lazy load javascripts, but I can't get it to work reliably. My pages load quite quickly and I want to keep it that way, so I'm not about to use a timeout to delay the loading. Besides document.readyState, how do I ensure the DOM is genuinely ready for modification?

Method I:

  1. poll readyState

  2. createElement script

  3. src = url

  4. appendElement to head

Results:

IE8: always aborts

FF3: loads first time, aborts every other

Chrome: loads first time, aborts every other

开发者_开发百科

Method II: (lazyload included in head tag)

  1. load with lazyload

Results:

IE8: always aborts

FF3: works

Chrome: loads first time, aborts every other


If you put your <script> tag just above the </body> tag, you could do most things with DOM without it raising any errors, i.e. anything that is above the <script> tag is usually up for modification.

However, if you are looking for a more robust solution, you might have some progress by checking out how the major libraries are detecting if the DOM is ready, here's one for starters (jQuery): http://github.com/jquery/jquery/blob/master/src/core.js#L393


Javascript is hardly usable cross-browsers without a decent framework to help you span the differences. Probably most popular today is jquery, where, per this tutorial, you could use $(document).ready(). In dojo, also quite popular, you could use addOnLoad. And so on... and if you aren't using any framework, you're making life too hard for yourself: do yourself a favor and pick a JS framework you like!-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜