【发布时间】: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?
【问题讨论】:
-
取自MDN,
The 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 谢谢,您的评论似乎回答了我的问题,与给出的答案不同。