Express单独服务js文件

express serve js files separately

本文关键字:文件 js 服务 单独 Express      更新时间:2023-09-26

使用express时,我的web应用程序加载速度太慢了。要服务的静态中间件我所有的js文件,所以我想尝试服务每个js文件只有在需要的时候(当服务从玉使用js文件的html)。我试过使用.sendFile(),但它似乎不起作用,虽然我不能告诉这是因为它不能用于我的目的,或者如果我只是不知道如何使用它。

是否有一种方法可以动态地提供js文件,以便在必要时不需要加载时间,或者我应该只是吸收它,最小化我的js,并在开始时静态地提供它?

我认为对你的问题最简单的解决办法是使用脚本标签中的Async属性

http://www.w3schools.com/tags/att_script_async.asp

 A script that will be run asynchronously as soon as it is available:
<script src="demo_async.js" async></script>

或者使用defer属性

http://www.w3schools.com/tags/att_script_defer.asp

A script that will not run until after the page has loaded:
<script src="demo_defer.js" defer></script>  

如果你在服务器上使用,设置nginx为服务静态文件:D