如何在页面加载后正确 运行 JS

How to correctly run JS after page loads

正在清理我的错误和贬值的网页,
我已 运行 收到此警告消息:

jquery-3.4.1.js:9725
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
For more help, check https://xhr.spec.whatwg.org/.

我想妥善处理JavaScript对:

  1. 将脚本和链接保存在独立区域中,即
  2. 运行 页面加载后


但我不知道如何:

  1. 将内联 JS 引用转换为 JS 文件
  2. 内部 JS 格式应该是什么样的



我一直在使用:

<head>

    <script>$(document).ready(function () { $('<script/>', { type: 'text/javascript', src: 'assets/js/set-background.js' }).appendTo('head'); }); </script>

</head>

使用 JS 文件:


...
var body = document.getElementsByTagName("body")[0];
body.className += " change-" + idx;
...

如果脚本是:

,则不会发生警告

<body>
    ...
    <script src="assets/js/set-background.js"></script>
    ...
</body>



并尝试过,

<head>

    <script>$(function(){'assets/js/set-background.js'}) </script>

</head>
<head>

    <script type="text/javascript" src="assets/js/set-background.js"></script>

</head>
<body class="container" onload="assets/js/set-background.js">



我看过其他开发者的讨论:

  1. javascript - How to run a function when the page is loaded? - Stack Overflow
  2. Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it - Stack Overflow
  3. javascript - $(document).ready equivalent without jQuery - Stack Overflow
  4. How to run a function in jquery - Stack Overflow


我也一直在阅读:

  1. onload Event
  2. .load() | jQuery API Documentation

此警告与页面加载无关。问题是你在某个地方使用了 XMLHttpRequest 和 'async' 参数 false.

这样不好,因为JS的事件循环行为(单线程),所以如果请求数据的下载时间较长,页面完全卡住:没有点击,滚动,其他JS功能,什么都没有!

要解决这个问题,你必须使用异步XMLHttpRequest,或者Web Workers