在HTML正文的末尾引用外部JavaScript文件时,如何调用JavaScript函数? [英] How to call a JavaScript function when the external JavaScript file is referenced at the end of the HTML body?

查看:50
本文介绍了在HTML正文的末尾引用外部JavaScript文件时,如何调用JavaScript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,当您想在HTML正文部分中调用JavaScript函数时,可以通过将< script>someFunction();</script> 在您的body标签内,这是一个示例,我有这样的HTML:

I know that when you want to invoke a JavaScript function inside a HTML body section you can do it by putting <script> someFunction(); </script> inside your body tag, here is an example, I have HTML like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<script type="text/javascript"
    src="/Script.js"></script>
</head>

<body>
    <script>
        showAlert();
    </script>
</body>

</html>

和如下所示的javascript文件:

And the javascript file like this:

function showAlert(){
    alert("This is an alert!");
}

这很好,但是如果我将JavaScript文件引用放在正文的末尾,如下所示:

This works fine but if I put the JavaScript file reference at the end of the body like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
</head>

<body>
    <script>
        showAlert();
    </script>
    <script type="text/javascript"
        src="/Script.js"></script>
</body>

</html>

不再调用函数 showAlert().您能回答以下两个问题吗?

the function showAlert() is no longer being invoked. Can you please answer these 2 questions:

  1. 为什么在第二种情况下未调用 showAlert()?
  2. 在以下情况下如何(如果可能)从JavaScript文件调用函数它是在正文末尾引用的吗?

我问的原因是因为我知道,在主体的末尾而不是头部引用JavaScript文件是一种好习惯,这样在加载所有JavaScript代码之前将首先呈现页面.

The reason why I'm asking is because I know that it is a good practice to refer your JavaScript files in the end of the body instead of the head, so that the page will be rendered first before loading all the JavaScript code.

推荐答案

假设您要在页面加载后立即运行showAlert(),请尝试添加onload()事件处理函数来调用showAlert,而不仅仅是将其作为脚本加载.这可以通过以下几种方式完成:

Assuming you want to run showAlert() immediately when the page has loaded, try adding an onload() event handler to call showAlert rather than just calling it as the script loads. This can be done a few ways:

<body onload="showAlert();">

或以编程方式定义窗口的onload事件,您当前的所有功能均在html中完成

or define the window onload event programatically where your current function all is made in the html

window.onload = new function() {showAlert();}

或(我认为这是首选方法,因为它不会取消绑定到onload事件的其他事件处理程序)

or (and I think this is the preferred way because it won't cancel out other event handlers bound to the onload event)

window.addEventListener("load", showAlert);

这篇关于在HTML正文的末尾引用外部JavaScript文件时,如何调用JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆