jQuery通过JS加载

时间:2013-05-02 15:41:18

标签: javascript jquery html jquery-mobile

我正在使用jQuery和jQuery Mobile来构建应用程序。我通过头部的脚本动态加载jQuery和jQuery Mobile。我的身体在脚本中使用jQuery($),但在异步加载时无法访问它。如何同步加载我的jQuery或解决问题?

提前致谢

1 个答案:

答案 0 :(得分:1)

您可能需要查看head.js。它异步加载你的脚本,然后给你一个就绪的函数,类似于jQuery,你可以放置所有的onLoad代码。

<head>
...
<script src="/js/head.js"></script>
<script>
    head.js('/js/jquery.js', '/js/jquery-mobile.js', function() {
        $(document).ready(function() {
            // Write some code!
        })
    });
</script>
...
</head>

如果您在其他地方需要javascript,可以使用head.ready()

<script>
    head.ready(function() {
        $(document).ready(function () {
            // Write more code!
        });
    });
</script>

哪个可以在html的任何地方。

注意:head.js示例不使用$(document).ready()中的jQuery head.ready(),但我记得没有它就遇到了一些问题。他们可能已经修好了,但包括它并没有真正伤害任何东西。

更新:正如评论中所述,对于jQuery Mobile,您应该使用$(document).bind('pageinit')代替$(document).ready()