Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - jQuery - 多个$(文档).ready ...?(jQuery - multiple $(document).ready …?)

Question:

(题:)

If I link in two JavaScript files, both with $(document).ready functions, what happens?

(如果我链接两个JavaScript文件,都带有$(document).ready函数,会发生什么?)

Does one overwrite the other?

(有人会覆盖另一个吗?)

Or do both $(document).ready get called?

(或者两个$(document).ready被调用?)

For example,

(例如,)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

<script type="text/javascript" src="http://.../jquery1.js"></script>

<script type="text/javascript" src="http://.../jquery2.js"></script>

jquery1.js :

(jquery1.js:)

$(document).ready(function(){
    $("#page-title").html("Document-ready was called!");
});

jquery2.js:

(jquery2.js:)

$(document).ready(function(){
    $("#page-subtitle").html("Document-ready was called!");
});


I'm sure it is best practice to simply combine both calls into a single $(document).ready but it's not quite possible in my situation.

(我确信最好将两个调用组合成一个$(document).ready但是在我的情况下它不太可能。)

  ask by rlb.usa translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All will get executed and On first Called first run basis!!

(一切都将被执行,并在第一次调用第一次运行的基础上!!)

<div id="target"></div>

<script>
  $(document).ready(function(){
    jQuery('#target').append('target edit 1<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 2<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 3<br>');
  });
</script>

Demo As you can see they do not replace each other

(演示如您所见,它们不会相互替换)

Also one thing i would like to mention

(还有一件事我想提一下)

in place of this

(代替这个)

$(document).ready(function(){});

you can use this shortcut

(你可以使用这个快捷方式)

jQuery(function(){
   //dom ready codes
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...