10
7
2011
53

document ready实现

转自:document ready实现

很多时候大家做前端时,需要在DOM树载入时马上执行一些函数,也就是实现document ready,而不是实现window.onload,比如对导航条进行初始化。但又不愿意仅为了这一个需求而引入整个jQuery库,于是就把 jQuery的ready方法提取出来,单独使用了。

代码如下:
(function(){
       var isReady=false//判断onDOMReady方法是否已经被执行过
       var readyList= [];//把需要执行的方法先暂存在这个数组里
       var timer;//定时器句柄
       ready=function(fn) {
              if (isReady )
                     fn.call( document);
              else
                     readyList.push( function() { return fn.call(this);});
              return this;
       }
       var onDOMReady=function(){
              for(var i=0;i<readyList.length;i++){
                     readyList[i].apply(document);
              }
              readyList = null;
       }
       var bindReady = function(evt){
              if(isReady) return;
              isReady=true;
              onDOMReady.call(window);
              if(document.removeEventListener){
                     document.removeEventListener("DOMContentLoaded", bindReady, false);
              }else if(document.attachEvent){
                     document.detachEvent("onreadystatechange", bindReady);
                     if(window == window.top){
                            clearInterval(timer);
                            timer = null;
                     }
              }
       };
       if(document.addEventListener){
              document.addEventListener("DOMContentLoaded", bindReady, false);
       }else if(document.attachEvent){
              document.attachEvent("onreadystatechange"function(){
                     if((/loaded|complete/).test(document.readyState))
                            bindReady();
              });
              if(window == window.top){
                     timer = setInterval(function(){
                            try{
                                   isReady||document.documentElement.doScroll('left');//在IE下用能否执行doScroll判断dom是否加载完毕
                            }catch(e){
                                   return;
                            }
                            bindReady();
                     },5);
              }
       }
})();

使用方式类下:

ready(navInit);//navInit为已存在的函数

ready(function(){
       if(agt.toLowerCase().indexOf("msie 6") != -1)
              navInitForIE6();//如果浏览器是IE6,则执行navInitForIE6函数来初始化下拉菜单
});

说明:

当我们想在页面加载之后执行某个函数,肯定会想到onload了,但onload在浏览器看来,就是页面上的东西(img,iframe等资源)全部都加载完毕后才能发生,如果页面内有大的图片的话,会在页面展现后好久时间后才执行。

如果只需要对DOM进行操作,那么这时就没必要等到页面全部加载了。我们需要更快的方法。有DOMContentLoaded事件可以轻松解决,可惜的就是IE没有。

关于JSCRIPT的一个方法有段不起眼的话,当页面DOM未加载完成时,调用doScroll方法时,会产生异常。那么我们反过来用,如果不异 常,那么就是页面DOM加载完毕了!这个函数是Diego Perini在07年就发布了这个名为IEContentLoaded的方法,而且获得了广泛认同,以至于现在许多开源框架都是借鉴这种方法,譬如 JQuery中的ready,在注释里有明确说明是有借鉴Diego Perini的IEContentLoaded方法。所以,对于Mozilla & Opera 浏览器,在dom树载入后有现成的 DOMContentLoaded 事件。

对于Safari 浏览器,有document.onreadystatechange事件,当该事件触发时,如果document.readyState=complete时,可视为dom树已经载入。

对于ie,当在iframe内时,同样有document.onreadystatechange事件,对于ie在非iframe内时,只有不断地 通过能否执行doScroll判断dom是否加载完毕。在本例中每间隔5毫秒尝试去执行 document.documentElement.doScroll('left')

另外要注意一点:在ie8下,貌视非iframe窗口也会有document.onreadystatechange事件

 

Category: Web摘记 | Tags: javascript jquery | Read Count: 3568
Avatar_small
لی ویوسوہ ہو یار 说:
2021年8月08日 01:18

Thanks for the blog post buddy! Keep them coming... movies123

Avatar_small
لی ویوسوہ ہو یار 说:
2021年8月14日 23:26

I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. <a href="https://www.4kweddingvideographer.com/">wedding videographer</a>

Avatar_small
jackjohnny 说:
2021年8月15日 20:05

Thanks, that was a really cool read! solarmoviess.art

Avatar_small
لی ویوسوہ ہو یار 说:
2021年8月17日 14:01

This was a really great contest and hopefully I can attend the next one. It was alot of fun and I really enjoyed myself.. 안전놀이터

Avatar_small
jackjohnny 说:
2021年8月18日 16:20

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. 123movies sites

Avatar_small
jackjohnny 说:
2021年8月18日 20:46

This blog is really great. The information here will surely be of some help to me. Thanks!. soap2day.com

Avatar_small
jackjohnny 说:
2021年8月19日 20:36

Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. click here

Avatar_small
لی ویوسوہ ہو یار 说:
2021年8月20日 18:03

It is a great website.. The Design looks very good.. Keep working like that!. Aesthetic.co.uk

Avatar_small
jackjohnny 说:
2021年8月23日 16:26

You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. thong tac cong gia lam

Avatar_small
jackjohnny 说:
2021年8月23日 21:43

You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this... smm panel theme

Avatar_small
seoservise 说:
2021年8月24日 15:54

What is an outstanding post! “I’ll be back” (to read more of your content). Thanks for the nudge! Dentitox Pro Reviews – After reading this, you should buy Dentitox Pro

Avatar_small
Pune Call Girls 说:
2021年8月25日 18:17

The reference you've got published is absolutely beneficial. The sites you have referred turned into pleasing. thank you for sharing.

Avatar_small
jackjohnny 说:
2021年8月28日 20:26

I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. satta

Avatar_small
لی ویوسوہ ہو یار 说:
2021年8月29日 23:41

I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. best binary options signals software

Avatar_small
لی ویوسوہ ہو یار 说:
2021年8月30日 03:25

Hey, this day is too much good for me, since this time I am reading this enormous informative article here at my home. Thanks a lot for massive hard work. Google Alternative

Avatar_small
jackjohnny 说:
2021年8月30日 19:22

Great articles and great layout. Your blog post deserves all of the positive feedback it’s been getting. matka chart

Avatar_small
jackjohnny 说:
2021年8月31日 23:25

Super-Duper site! I am Loving it!! Will come back again, Im taking your feed also, Thanks. matka

Avatar_small
jackjohnny 说:
2021年9月04日 16:28

This is very interesting content! I have thoroughly enjoyed reading your points and have come to the conclusion that you are right about many of them. You are great. kalyan satta

Avatar_small
jackjohnny 说:
2021年9月05日 20:31

It was wondering if I could use this write-up on my other website, I will link it back to your website though.Great Thanks. voyance par tel

Avatar_small
jackjohnny 说:
2021年9月06日 22:41

really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot! water based PU

Avatar_small
jackjohnny 说:
2021年9月08日 17:39

When you use a genuine service, you will be able to provide instructions, share materials and choose the formatting style. BVMW

Avatar_small
seoservise 说:
2021年9月08日 21:46

I really like your take on the issue. I now have a clear idea on what this matter is all about.. 250 dofollow blog comments

Avatar_small
jackjohnny 说:
2021年9月11日 21:51

Love to read it,Waiting For More new Update and I Already Read your Recent Post its Great Thanks. 바둑이게임

Avatar_small
matka satta 说:
2021年9月12日 14:42

I think this is a better than average article. You make this data intriguing and locks in. You give perusers a considerable measure to consider and I welcome that sort of composing

Avatar_small
matka result 说:
2021年9月13日 18:08

Thank you for the update, very nice site..

Avatar_small
seoservise 说:
2021年9月14日 20:40

Yes, I am entirely agreed with this article, and I just want say that this article is very helpful and enlightening. I also have some precious piece of concerned info !!!!!!Thanks. sitio web

Avatar_small
jackjohnny 说:
2021年9月14日 22:48

to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks ไฮโลออนไลน์

Avatar_small
golden matka 说:
2021年9月15日 16:30

The website is looking bit flashy and it catches the traffic eyes. layout is beautiful clean and a enjoyable adherent without problems reached interface.

Avatar_small
balance-sheet 说:
2021年9月16日 22:35

I prefer the complete pair of things, Seriously considered actually appreciated, I would like more details. with this, contemplating it is relatively respectable., Thank you a whole lot when it comes to exhibiting.

Avatar_small
pandoralistens 说:
2021年9月18日 23:56

Thanks for taking the length to claim this suggestion especially beneficial!

Avatar_small
jackjohnny 说:
2021年9月21日 20:17

The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. 먹튀폴리스

Avatar_small
satta matka 说:
2021年9月26日 18:21

Thanks so much for sharing this awesome info! I am looking forward to see more postsby you!

Avatar_small
sattamatka 说:
2021年9月28日 18:54

That is the excellent mindset, nonetheless is just not help to make every sence whatsoever preaching about that mather. Virtually any method many thanks in addition to i had endeavor to promote your own article in to delicius nevertheless it is apparently a dilemma using your information sites can you please recheck the idea. thanks once more.

Avatar_small
satta 说:
2021年9月30日 15:13

I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before.

Avatar_small
matka 说:
2021年10月02日 19:03

tremendous web page, where did u arrive occurring thinking of the opinion within the region of this posting?i've right of proper of right of access some of the articles approaching your website now, and that i in truth subsequent to your fashion. thank you a million and absorb save taking vicinity the energetic institution.

Avatar_small
krogerexperiencee fu 说:
2021年10月02日 23:47

I was very impressed by this post, this site has always been pleasant news Thank you very much for such an interesting post, and I meet them more often then I visited this site

Avatar_small
food near me 说:
2021年10月04日 19:02

I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy.

Avatar_small
jackjohnny 说:
2021年10月04日 21:34

When you use a genuine service, you will be able to provide instructions, share materials and choose the formatting style. voyance sans attendre

Avatar_small
Digital Ali 说:
2021年10月08日 15:19

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work. cheap transcription services

Avatar_small
Digital Ali 说:
2021年10月09日 19:08 I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best! คาสิโนออนไลน์ฟรีเงิน
Avatar_small
seoservise 说:
2021年10月10日 16:50 Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers. 검증사이트
Avatar_small
Digital Ali 说:
2021年10月11日 12:39

Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. thor costume men

Avatar_small
link 说:
2021年10月12日 18:56

We have sell some products of different custom boxes.it is very useful and very low price please visits this site thanks and please share this post with your friends. North American Bancard Agent Program

Avatar_small
mynorthsidehr 说:
2021年10月18日 15:02

"I love the way you write and share your niche! Very interesting and different! Keep it coming! "

Avatar_small
seoservise 说:
2021年10月26日 02:51

Nice knowledge gaining article. This post is really the best on this valuable topic. voyance telephone

Avatar_small
Digital Ali 说:
2021年10月27日 13:49 Whenever I have some free time, I visit blogs to get some useful info. Today, I found your blog with the help of Google. Believe me; I found it one of the most informative blog. adjustable dumbbells
Avatar_small
Digital Ali 说:
2021年11月06日 03:52

Thank you for some other informative blog. Where else could I get that type of information written in such an ideal means? I have a mission that I’m just now working on, and I have been at the look out for such information. link pkv games

Avatar_small
インドのビザ 说:
2021年11月13日 19:31

Great post, you have pointed out some excellent points, I as well believe this is a very superb website.

Avatar_small
wedding photographer 说:
2021年11月20日 17:53

cool stuff you have got and you keep update all of us.

Avatar_small
Βίζα Καναδά Online 说:
2021年11月28日 22:49

Every year, thousands of customers around the world choose MaroCar for a cheap car hire in Morocco. The platform operates in the main cities of the kingdom (Casablanca, Marrakech, Tangiers, Rabat ...) and delivers its cars to the address of your choice or directly to the main airports in the country.

Avatar_small
sasa 说:
2022年8月31日 03:15

Very nice article, I enjoyed reading your post, very nice share, I want to twit this to my followers. Thanks!. formation gestion d'entreprise

Avatar_small
akak 说:
2022年10月29日 23:46

A very excellent blog post. I am thankful for your blog post. I have found a lot of approaches after visiting your post. gramhir

Avatar_small
SEO 说:
2023年9月05日 17:56

Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks EuroTogel Login


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com