在DOM之后加载jQuery,如何在加载jQuery之前使$ .ready()可用于我的页面?
我想迟到加载jQuery,但我在$ .ready()上运行了少量的内联javascript。 由于没有加载jQuery,这些行会抛出错误并且永远不会运行。 有没有办法让$ .ready()成为一个可用的函数,但等待执行直到加载jQuery?
谢谢!
解决此问题的一般方法的一个选项是将内联javascript放在函数中,并将该函数添加到全局可访问的数组中 – 不要调用它。 这些本质上是在document.ready
可用时要为document.ready()
安排的函数。
然后,当你加载jQuery时,你设置了一个document.ready()
处理程序,它循环遍历该数组中的所有函数并调用它们。
// declare global at the top of your web page var readyFns = []; // in your inline code, add a function to the readyFns array readyFns.push(myInlineFn); // when your jQuery code loads, do this: $(document).ready(function() { for (var i = 0; i < readyFns.length; i++) { readyFns[i](); } });
如果你想使用匿名函数,你可以像这样做中间步骤:
// in your inline code, add a function to the readyFns array readyFns.push(function() { // put your code here });
而不是使用.ready
,你可以使用非jQuery等价物,例如window.onload
,但这些与.ready
有点不兼容,所以我不确定它们是否能满足你的需求。
有人显然已经提取了jQuery的就绪function,因此它可以单独使用: http : //code.google.com/p/domready/
你应该:
- 用函数调用替换ready,例如
example();
- 创建一个函数,例如
example() { }
- 将该函数放入
(document).ready()