草庐IT

javascript - window.onload 事件不触发或 "how to properly initialize js project?"

coder 2023-08-10 原文

这个问题似乎很常见,但我找不到答案。

我有这个简单的 html,只有 canvas 标签

<!doctype html>

  <head>
    <meta charset = "utf-8">
    <script src="js/script.js"></script>
    <title>Title</title>
  </head>

  <body>
    <canvas id = "canvas"></canvas>  
  </body>

</html>

在 script.js 中我试图捕捉 window.onload 事件:

window.onload = init;

function init(){
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");

  context.fillRect(50, 20, 150, 150);
}

但是没有任何反应。我假设 html 甚至在第一行 js 执行之前就已加载。

所以我发现 onload 事件的替代方法是将脚本定义放在主体的末尾,这样当脚本被执行时,窗口应该已经加载。所以我这样做了:

<!doctype html>

  <head>
    <meta charset = "utf-8">   
                                  <!-- gone -->
    <title>Title</title>
  </head>

  <body>
    <canvas id = "canvas"></canvas> 
    <script src="js/script.js"></script>  <!-- inserted -->
  </body>

</html>

<!-- window.onload = init; -->
init()                              <!-- inserted -->

function init(){
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");

  context.fillRect(50, 20, 150, 150);
}

在某种程度上它可以工作(绘制矩形),但给我一个错误Uncaught ReferenceError: context is not defined

所以我的问题是我做错了什么?我也想知道是否有更好的方法来做到这一点。

附言我倾向于不使用 jquery...

已编辑:上下文错误与上面的代码无关,尽管我仍然不喜欢将 js 文件的链接放在正文末尾的想法...

最佳答案

这里,试试下面的代码。关键点是:

(1) 您可以指定 1 个以上的函数在 onload 事件触发时运行。 (2) 你可以把它们贴在任何你喜欢的地方。当附加事件触发时,它们仍然会被调用。但是-我认为不能保证功能将按照附加的顺序执行。使用 addEventListener 将多个函数附加到单个事件时请记住这一点。

无论如何,输出是:

created with function called from **test.js**
created with function called from test.html
created with function called from **test.js**

test.html

<!doctype html>
<html>
<head>
<script src='test.js'></script>
<script>
window.addEventListener('load', mInlineJsLoadFunc, false);
function mInlineJsLoadFunc()
{
    var div = document.createElement('div');
    div.appendChild( document.createTextNode('created with function called from test.html') );
    document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
</body>
<script src='test.js'></script>
<html>

test.js

window.addEventListener('load', mExternalJsLoadFunc, false);
function mExternalJsLoadFunc()
{
    var div = document.createElement('div');
    div.appendChild( document.createTextNode('created with function called from **test.js**') );
    document.body.appendChild(div);
}

关于javascript - window.onload 事件不触发或 "how to properly initialize js project?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393081/

有关javascript - window.onload 事件不触发或 "how to properly initialize js project?"的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  5. ruby - 触发器 ruby​​ 中 3 点范围运算符和 2 点范围运算符的区别 - 2

    请帮助我理解范围运算符...和..之间的区别,作为Ruby中使用的“触发器”。这是PragmaticProgrammersguidetoRuby中的一个示例:a=(11..20).collect{|i|(i%4==0)..(i%3==0)?i:nil}返回:[nil,12,nil,nil,nil,16,17,18,nil,20]还有:a=(11..20).collect{|i|(i%4==0)...(i%3==0)?i:nil}返回:[nil,12,13,14,15,16,17,18,nil,20] 最佳答案 触发器(又名f/f)是

  6. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  7. ruby-on-rails - Rails - 乐观锁定总是触发 StaleObjectError 异常 - 2

    我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd

  8. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  9. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  10. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

随机推荐