在DOM之后加载jQuery,如何在加载jQuery之前使$ .ready()可用于我的页面? [英] Load jQuery after DOM, how can I make $.ready() available to my page before jQuery is loaded?

查看:68
本文介绍了在DOM之后加载jQuery,如何在加载jQuery之前使$ .ready()可用于我的页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想迟到加载jQuery,但我在$ .ready()上运行少量的内联javascript。由于没有加载jQuery,这些行会抛出错误并且永远不会运行。有没有办法让$ .ready()成为一个可用的函数,但等待执行直到加载jQuery?

I want to late load jQuery, but I have a small amount of inline javascript the runs on $.ready(). Since jQuery isn't loaded, these lines throw an error and never run. Is there a way I can make $.ready() an available function, but wait on execution until jQuery is loaded?

谢谢!

推荐答案

解决此问题的一般方法的一个选项是将内联javascript放入函数中并将该函数添加到全局可访问的数组中 - 不要调用它然而。当 document.ready 可用时,这些基本上是您要为 document.ready()安排的函数。

One option for a generic way to solve this is to put your inline javascript in a function and add that function to a globally accessible array - don't call it yet. These are essentially functions that you want to schedule for document.ready() when document.ready is available.

然后,当你加载jQuery时,你设置一个循环遍历所有函数的 document.ready()处理程序在该数组中调用它们。

Then, when you do load jQuery, you set up a document.ready() handler that cycles through all the functions in that array and calls them.

// 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]();
    }
});

如果你想使用匿名函数,你可以像这样做中间步骤:

If you want to use anonymous functions, you can do the middle step like this:

// in your inline code, add a function to the readyFns array
readyFns.push(function() {
   // put your code here
});

这篇关于在DOM之后加载jQuery,如何在加载jQuery之前使$ .ready()可用于我的页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆