[英]jQuery + head.js: How to trigger $(document).ready() manually from inside ready callback of head.js?
我需要优化Web应用程序的加载时间,该应用程序包含每个HTML页面中包含的大量javascript文件。 我想在一个这样的页面中尝试head.js ,看看它是否会改善加载时间。 这些JS文件中有很多$(document).ready(callback)
回调函数,这些函数在加载DOM时调用,而head.js仍在下载剩余的JS文件。
有没有办法告诉jQuery不要自己触发ready
事件,而是让我从head.js的ready回调中触发它?
我做了一个小实验。 就像是:
<html>
<head>
<script src="head.js"></script>
<script src="jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
jQuery("document").ready(function() {
console.log("ready.document");
});
</script>
...
<script type="text/javascript">
head.js("a.js", "b.js", "c.js", "test.js", function() {
console.log("init.scripts");
var millis = 2000;
var date = new Date();
var curDate = null;
do {curDate = new Date(); }
while(curDate-date < millis);
jQuery("#ddd").text(testTT);
console.log("init.end");
});
</script>
... a lot of html content ...
<div id="ddd"></div>
...
<script type="text/javascript" >
console.log("last line");
</script>
</body>
test.js写入控制台并定义testTT 。 结果如下
last line
init.testTT
init.scripts
init.end
ready.document
因此,在这个简单的情况下(使用jQuery 1.8),首先执行加载的* .js中的代码,然后生成init事件上的head.js,最后生成jQuery ready事件。 所以等到JQuery生成就绪事件应该没问题。 但是,如果这仍然是一个问题,您可以执行以下操作。
head.js("a.js", "b.js", "c.js", function() {
jQuery("document").ready(function() {
jQuery("body").trigger("your_event");
});
});
而不是听jQuery("document").ready...
在你的* .js中开始听你正在触发jQuery("body").on("your_event", handler)
的自定义事件。
创建一个函数在文档就绪中注册它
$(document).ready(readyFunc);
readyFunction(){
/// something to do;
}
如果你想手动使用它们,只需要调用readyFunction();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.