即使我将脚本标记放在body标记的末尾,Google Chrome也会先加载javascript [英] Google Chrome loads the javascript first even I put the script tag before the end of the body tag

查看:104
本文介绍了即使我将脚本标记放在body标记的末尾,Google Chrome也会先加载javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在Google Chrome中加载JavaScript时遇到问题。

我用一个简单的警告信息创建了单独的js文件,然后在body标记结束之前将其链接起来。

谷歌浏览器首先显示警告框然后单击确定加载内容。

在其他浏览器中,它工作正常,我的意思是警报框与网页内容同时显示。

简而言之,即使我将脚本标记放在body标记的末尾之前,Google Chrome也会首先加载javascript。


I have a problem with loading JavaScript in Google Chrome.
I've created the separate js file with a simple alert message and then linked it before the end of the body tag.
Google Chrome shows the alert box first then when I click 'ok' the content is loaded.
In other browsers it works fine, I mean the alert box shows at the same time as the content of the web page.
In short, Google Chrome loads the javascript first even when I put the script tag before the end of the body tag.

alert("Hello World!");

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Write Your First Program</title>
    <!-- Bootstrap Core CSS -->
      <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom CSS -->
     <link href="css/styles.css" rel="stylesheet">

</head>
<body>
    <!-- Header -->
     <header class="header">
        <div class="text-vertical-center">
            <h1>Write Your First Program</h1>
            <h3>JavaScript Essentials</h3>
            <br>
        </div>
    </header>

<script src="js/scripts.js"></script>
</body>
</html>

你知道如何解决这个问题吗?
非常感谢

Do you have any idea how to fix this problem? Thanks a lot

推荐答案

您的问题是您的脚本标记为 async ,让它执行whitout来处理网页加载状态。删除 async 标记,或将其替换为 defer ,它在页面加载后执行脚本。

Your problem is that your script have the tag async, which let it execute whitout taking care of the web page loading state. Remove the async tag, or replace it with defer, which execute the script after the page loading.

为了防止脚本和html / css加载时间冲突的任何问题,你应该用窗口封装 Javascript 的脚本.onload = function(){// code here} 。这将保证在执行代码之前加载整个页面。

In order to prevent any problem with script and html/css loading times conflict, you should encapsulate your Javascript's scripts with window.onload = function() { //code here }. This will guarantee that your whole page is loaded before executing your code.

这篇关于即使我将脚本标记放在body标记的末尾,Google Chrome也会先加载javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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