-1
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>
        <h1>Welcome</h1>


        <script>
            $(function() {
                // $ is undefined
            });
        </script>
        <script src="js/jquery.js"></script>
    </body>
</html>

有没有办法在执行函数之前等待文档加载并加载jQuery?

4

4 回答 4

5

$在它存在之前引用它,那根本行不通。

假设js/jquery.js存在,这将起作用:

<script src="js/jquery.js"></script>
<script>
        $(function() {
            // your code goes here
        });
</script>

因为第一个脚本标记将$在第二个引用它之前定义。

无需等待文件准备好

Hattip 向@KevinB 指出这一明显的附加点。

如果脚本标签在头部 - 加载脚本时正文不存在。出于这个原因,在运行 javascript 之前使用 document ready 来确保 html 页面存在是很常见的。

如果脚本标签位于页面底部,则在加载脚本时 html 已经存在,因此无需等待文档就绪事件。因此,js代码变为:

<script src="js/jquery.js"></script>
<script>
         // your code goes here
</script>
</body>
</html>
于 2013-07-19T19:36:25.620 回答
1

我觉得这不是一个好的解决方案,但如果您真的需要,您可以加载 jQuery,类似于 Google 为他们的分析服务加载 JavaScript 的方式。您可以在之后编写更多代码来检测它何时完成加载并执行包含您想要执行的回调。

从本网站http://www.tlswebsolutions.com/how-to-include-jquery-dynamically-aka-check-to-see-if-it-exists/获取和修改的粗略演示

if(!(window.jQuery)) {
    var s = document.createElement('script');
    s.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
    s.setAttribute('type', 'text/javascript');
    document.getElementsByTagName('head')[0].appendChild(s);
}
于 2013-07-19T19:49:28.540 回答
0

为您简化 -

<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>Welcome</h1>

    <script src="js/jquery.js"></script>

    <script>
        $(function() {
            // $ is undefined
        });
    </script>
</body>

于 2013-07-19T19:37:49.030 回答
0

从技术上讲,你可以。

function main() {
  if (! window.jQuery) {
    setTimeout(main, 100);
    return;
  }
  // Some code that uses jQuery
}

setTimeout(main, 100);

这似乎也是可能的,但在旧浏览器上可能无法可靠地工作。

window.onload = function() {
  // Some code that uses jQuery
};
于 2013-07-19T19:45:01.057 回答