【问题标题】:Does window.onload guarantee that jQuery will be defined?window.onload 是否保证将定义 jQuery?
【发布时间】:2016-12-26 01:29:21
【问题描述】:

我有以下设置:

header.ejs

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap 101 Template</title>
        <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>

page.ejs

<%- include ../partials/header -%>

<!-- some HTML code -->

<script>
// error: $ is not defined
$(function () { });

window.onload = function () {
    // $ is defined
}
</script>

<%- include ../partials/footer -%>

footer.ejs

        <script src="/jquery/jquery.min.js"></script>
        <script src="/bootstrap/js/bootstrap.min.js"></script>
    </body>
</html>

目前,内联 JS 代码仅在我使用 window.onload 时有效。没有它,我的控制台中会出现一条错误消息$ is not defined。我知道代码必须放在footer.ejs 中的 jquery 脚本标记之后才能正常工作。

我的问题是使用window.onload 是否如我的示例中所示保证jQuery 将在其回调中定义?当window.onload 被解雇时,jQuery 是否有可能成为undefined

【问题讨论】:

  • 取自MDNThe load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
  • @choz 谢谢,您的评论似乎回答了我的问题,与给出的答案不同。

标签: jquery node.js onload ejs


【解决方案1】:

如果您想保证在执行任何操作之前加载 jQuery,请将您的 JS 包装在 jQuery 的 document ready 方法中:

jQuery(document).ready(function($){
  // Run your jQuery here...
});

只有在浏览器中请求、加载和执行 jQuery 时,才会调用在该块中运行的任何 JS。

【讨论】:

  • 这仅在代码块放置在页脚中的 jQuery 脚本标记之后才有效。否则,jQuery is not defined。无论如何,choz 的评论似乎回答了我的问题。谢谢你。
猜你喜欢
  • 2012-02-06
  • 2011-01-17
  • 2015-09-17
  • 2012-06-02
  • 1970-01-01
  • 2017-09-30
  • 2015-08-13
  • 1970-01-01
  • 2011-01-24
相关资源
最近更新 更多