【问题标题】:How to correctly run JS after page loads页面加载后如何正确运行JS
【发布时间】:2019-06-17 01:58:33
【问题描述】:

正在清理我的错误和折旧的网页,
我遇到了这个警告信息:

jquery-3.4.1.js:9725
[弃用] 主线程上的同步 XMLHttpRequest 已弃用,因为它会对最终用户的体验产生不利影响。
如需更多帮助,请查看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

【问题讨论】:

  • 这是正确的:
  • 这个不行,问题是我需要在页面加载后运行脚本。

标签: javascript jquery html onload document-ready


【解决方案1】:

此警告与页面加载无关。问题是您在某处使用了带有“异步”参数falseXMLHttpRequest

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

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

【讨论】:

  • 好的,那么如何找到 XMLHttpRequest?直到我尝试重新格式化代码,警告才发生,而且我不熟悉隐式异步参数的位置。
  • @zach 搜索类似:xhr=new XMLHttpRequest(); xhr.open(/*something*/,/*something*/,false)。而且你不能在评论中创建换行符;)
  • @zach 或者如果你使用 jQuery,它可能是 $.ajax
猜你喜欢
  • 1970-01-01
  • 2011-11-10
  • 2011-10-08
  • 2014-06-19
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多