简体   繁体   English

如何在 HTML 正文末尾引用外部 JavaScript 文件时调用 JavaScript 函数?

[英]How to call a JavaScript function when the external JavaScript file is referenced at the end of the HTML body?

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>我知道当你想在 HTML 正文部分调用一个 JavaScript 函数时,你可以通过把<script> someFunction(); </script> <script> someFunction(); </script> inside your body tag, here is an example, I have HTML like this: <script> someFunction(); </script>在你的 body 标签中,这是一个例子,我有这样的 HTML:

<!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>

And the javascript file like this:和这样的 javascript 文件:

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

This works fine but if I put the JavaScript file reference at the end of the body like this:这工作正常,但如果我将 JavaScript 文件引用放在正文的末尾,如下所示:

<!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>

the function showAlert() is no longer being invoked.不再调用函数showAlert() Can you please answer these 2 questions:能否请您回答以下2个问题:

  1. Why is showAlert() not invoked in the second scenario?为什么在第二种情况下没有调用showAlert()
  2. How (if possible) to invoke a function from a JavaScript file when it is referenced in the end of the body?如何(如果可能)在主体的末尾引用 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.我之所以这么问是因为我知道在正文的末尾而不是在头部引用 JavaScript 文件是一个很好的做法,这样页面将在加载所有 JavaScript 代码之前首先呈现。

1) The scripts are loaded linearly. 1) 脚本是线性加载的。 Since the script has not yet been loaded, the function is undefined.由于脚本尚未加载,函数未定义。 (This is in contrast to function hoisting within a script.) (这是在脚本的对比函数吊装。)

2) Simply wait till the page loads. 2)只需等待页面加载。

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

(Simply doing window.onload = showAlert won't work because of reason #1. Here you delay evaluation until such time that the function will exist.) (简单地做window.onload = showAlert由于原因 #1 将不起作用。在这里你延迟评估直到函数存在的时间。)

Javascript processes in the order given. Javascript 按照给定的顺序进行处理。 You are trying to call showAlert before showAlert have been defined.您试图在定义 showAlert 之前调用 showAlert。 Change to:改成:

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

and all should work as intended.并且一切都应该按预期工作。

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.假设您想在页面加载后立即运行 showAlert(),请尝试添加一个 onload() 事件处理程序来调用 showAlert,而不是仅在脚本加载时调用它。 This can be done a few ways:这可以通过几种方式完成:

<body onload="showAlert();">

or define the window onload event programatically where your current function all is made in the html或以编程方式定义窗口 onload 事件,其中您当前的功能都在 html 中完成

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

or (and I think this is the preferred way because it won't cancel out other event handlers bound to the onload event)或者(我认为这是首选方式,因为它不会取消绑定到 onload 事件的其他事件处理程序)

window.addEventListener("load", showAlert);

By default, scripts run sequentially.默认情况下,脚本按顺序运行。 Your code doesn't work because showAlert() runs before loading Script.js , so at that point the function showAlert is not defined yet.您的代码不起作用,因为showAlert()在加载Script.js之前运行,因此此时函数showAlert尚未定义。

To make it work, you must delay the showAlert call.要使其工作,您必须延迟showAlert调用。

The load event has already been mentioned in other answers, but it will wait for all resources (like images) to load. load事件已经在其他答案中提到过,但它会等待所有资源(如图像)加载。 So listening to the DOMContentLoad event is usually better, the function will be called sooner.所以监听DOMContentLoad事件通常会更好,该函数会被更快地调用。

 <script> document.addEventListener('DOMContentLoaded', function() { showAlert(); }); </script> <script src="data:text/javascript, function showAlert() { console.log('Hello!') } "></script>

The reason for your script isn't working is the way how a webpage is parsed.. From top to bottom ..Here is some link (would help to know why script added at bottom).您的脚本不起作用的原因是网页的解析方式..从上到下..这是一些链接(有助于了解为什么在底部添加脚本)。

1) in your First case the browser loaded script when it parsed the page and when you called it in body it was available so it got invoked. 1)在您的第一种情况下,浏览器在解析页面时加载脚本,当您在正文中调用它时,它可用,因此它被调用。

2) in Second scenario (My be typo) You have placed the call to function before loading the script that contain your function. 2)在第二种情况下(我是错别字)您在加载包含您的函数的脚本之前已经调用了函数。 so during page parsing browser wont find it and continue to next line where script containing function is loaded which has no effect for now as it already parsed the call.所以在页面解析浏览器不会找到它并继续到下一行加载包含函数的脚本,因为它已经解析了调用,所以现在没有任何影响。

If you still want to follow the second scenario you have to trigger the function call (after ensuring all resources being loaded ie Your script).如果您仍然想遵循第二种情况,您必须触发函数调用(在确保加载所有资源后,即您的脚本)。 so you can use window.load=<your function call> or in case of jQuery place it inside所以你可以使用window.load=<your function call>或者在 jQuery 的情况下把它放在里面

$(document).ready(function(){
//call here
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM