简体   繁体   English

中的RequireJS脚本标签 <head> 还是页面底部?

[英]RequireJS script tag in <head> or at bottom of page?

Should the RequireJS script tag be located in the <head> or bottom of an HTML page? RequireJS脚本标记应该位于HTML页面的<head>还是底部?

<script data-main="resources/js/main" src="require.js"></script>

I have seen reputable sources place the RequireJS script tag in either position, but no reputable source seems to explicitly say where the ideal location is. 我已经看到有信誉良好的消息源将RequireJS脚本标签放在任一位置,但是似乎没有信誉良好的消息源明确说明理想位置在哪里。

Arguments for placing the tag in the head would be that RequireJS could already begin loading and executing dependent scripts asynchronously while the page continues loading (though this gain may be minuscule). 标签放在头部的说法是,RequireJS可以在页面继续加载的同时就开始异步加载和执行相关脚本(尽管这种收获可能微不足道)。

Arguments for placing the tag at the bottom of the page would be that checks for the DOM being ready wouldn't be needed within modules (though not including this check may cause problems if the module is used in a third-party system that loads the script in the <head> tag). 标签放置在页面底部的理由是,不需要在模块内检查DOM是否准备就绪(尽管如果不使用此检查,则如果该模块在加载了DOM的第三方系统中使用,可能会导致问题。 <head>标记中的脚本)。

General best practice is to always place your script at the bottom. 一般的最佳做法是始终将脚本放在底部。

You may have seen people including it in the HEAD as it is not doing a big difference. 您可能已经看到有人将其包含在HEAD中,因为它没有太大的不同。

I'd recommend in the bottom, because as you'll want to build your scripts before production, you'll end up loading all your script in the head otherwise. 我建议在底部,因为您要在生产之前构建脚本,否则最终将所有脚本加载到头部。

Note that if you're running a "single page application", then it really doesn't matter as chances are your body will be empty - or almost empty. 请注意,如果您正在运行“单页应用程序”,那么这实际上并不重要,因为您的身体很可能是空的-或几乎是空的。

Put it at the bottom of the page, it's better for performance and if you're planning to manipulate the page (as expected) then you want it to load the page first anyway. 将其放在页面底部,可以提高性能,如果您打算按预期操作页面,则无论如何都希望它首先加载页面。

Best practice, with few exceptions, is always: 除了少数例外,最佳实践始终是:

  • Load styles (css) 加载样式(css)
  • Load structure (html) 负载结构(html)
  • Load scripts (functionality) 加载脚本(功能)

I'm working on a project with a lot of templates and about 1MB of js on page load, and putting requireJS at the top of the page has it's perks. 我正在一个项目上,该项目包含许多模板,页面加载时包含大约1MB的js,将requireJS放在页面顶部具有特权。 Require can start scheduling and parsing js while the rest of the html downloads. Require可以开始计划和解析js,而其余的html下载。 Also, we have noticed that, this allows us to 'require' css in the page before all of the html comes down. 另外,我们注意到,这使我们能够在所有HTML都没有下来之前“请求”页面中的CSS。

I did find one caveat today, where script tags might execute twice if require is loaded in the page at the head/ before the script tag. 我今天确实发现了一个警告,如果在脚本标记的head /之前的页面中加载了require,则脚本标记可能会执行两次。 I'm trying to create an example to debug. 我正在尝试创建一个示例进行调试。

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

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