简体   繁体   English

加载脚本是否会动态阻止渲染?

[英]Does loading scripts dynamically block the rendering?

I'm trying to load bootstrap.min.js file. 我正在尝试加载bootstrap.min.js文件。 I have two options. 我有两个选择。 The first one is to load it from a remote server: 第一个是从远程服务器加载它:

 <!DOCTYPE html> <html lang='ru'> <head> <meta charset='utf-8'> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> </head> <body> ... </body> </html> 

The second one is to load it from my server: 第二个是从我的服务器加载它:

 <!DOCTYPE html> <html lang='ru'> <head> <meta charset='utf-8'> <script src="js/bootstrap.min.js"></script> </head> <body> ... </body> </html> 

In the first case the script will load asynchronously which means the rendering of my page won't be blocked. 在第一种情况下,脚本将异步加载,这意味着不会阻止我页面的呈现。 In the second case the script will block the rendering of my page. 在第二种情况下,脚本将阻止我的页面的呈现。 Am I correct? 我对么?

How will blootstrap.min.js be loaded (async or sync) if I try to do this : 如果我尝试这样做,如何加载blootstrap.min.js(异步或同步):

 <!DOCTYPE html> <html lang='ru'> <head> </head> <body> <script> var bootstrap = document.createElement('script'); bootstrap.src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"; var head = document.getElementsByTagName('head')[0]; head.appendChild(bootstrap); </script> ... </body> </html> 

And this: 和这个:

 <!DOCTYPE html> <html lang='ru'> <head> </head> <body> <script> var bootstrap = document.createElement('script'); bootstrap.src = "js/bootstrap.min.js"; var head = document.getElementsByTagName('head')[0]; head.appendChild(bootstrap); </script> ... </body> </html> 

I have a hunch that in both cases the rendering won't be blocked. 我有一种预感,在这两种情况下都不会阻止渲染。 What do you think? 你怎么看? Thanks! 谢谢!

If you put the source-loading code at the end of your <body> tag, the rendering won't be blocked, even though the new script tags are appended to the head. 如果将源加载代码放在<body>标记的末尾,则即使将新script标记附加到头部,也不会阻止呈现。 That's because most of the rendering is already done when you get to that part. 这是因为当您到达该部分时,大多数渲染已经完成。

In newer browsers , you can add an async attribute to the script tag, which will not block rendering. 在较新的浏览器中 ,您可以向脚本标记添加async属性,这不会阻止呈现。 So I suspect loading the file asynchronously via JS will not block rendering either, even if you do it near the top of the file. 所以我怀疑通过JS异步加载文件也不会阻止渲染,即使你在文件顶部附近也是如此。

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

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