简体   繁体   English

为什么不动态添加脚本阻止加载页面的其余部分

[英]Why doesn't dynamically added script block the rest of the page from loading

I have a simple page: 我有一个简单的页面:

<!DOCTYPE html>
<html>
<head>
  <script>
    func = function(message) {
       alert(message);
    }
  </script>
</head>
<body>
  <h1> Visible content </h1>
</body>
</html>

and a script which is in separate file -- let's say -- test.js : 还有一个位于单独文件中的脚本-假设test.js

func("It should block the page.");

When I simply add this script to head by typing: 当我简单地通过键入以下内容将此脚本添加到头部时:

<script src="test.js"></script>

Alert shows before the content is visible which is fine to me. 在内容可见之前显示警报,这对我来说很好。
However when I add the script dynamically: 但是,当我动态添加脚本时:

<script>
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('src', 'test.js');
  document.getElementsByTagName('head')[0].appendChild(script);
</script>

Alert shows after the content. 警报显示在内容之后。

Why does that happen? 为什么会这样呢? Shouldn't the browser wait untill the script finishes (including adding and loading a new one)? 浏览器难道不应该等脚本完成(包括添加和加载新脚本)后再等待吗? Is it possible to block the body content with dynamically added script? 是否可以使用动态添加的脚本来阻止正文内容?

It happens because of asynchronous loading. 这是由于异步加载而发生的。 Have a look at the article: http://css-tricks.com/thinking-async/ 看一下文章: http : //css-tricks.com/thinking-async/

It depends what do you mean by blocking . 这取决于您所说的封锁是什么意思。 You can load the page with the content block hidden: <div style="display:none;"></div> and show it after the page is loaded. 您可以使用隐藏的内容块加载页面: <div style="display:none;"></div>并在页面加载后显示它。

Here's jQuery way: 这是jQuery的方式:

$(function () {
    // do stuff after DOM has loaded
});  

Have a look at this answer for more: javascript domready? 进一步了解此答案: javascript domready?

Wrap it in document.ready: 将其包装在document.ready中:

$(document).ready(function () {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('src', 'test.js');
  document.getElementsByTagName('head')[0].appendChild(script);
});

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

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