将 javascript 添加到页面或外部 javascript 文件
我有我在 javascript 中使用的一些 javascript 变量(即外部 javascript 文件)
此 javascript 变量是特定于页面的,并且因页面和用户而异。
最好将这些放在任何其他 javascript 文件中,这意味着额外的 http 请求,还是将其包含在页面的 html 内容中,从而使页面膨胀。
我喜欢分离,但希望尽一切努力最大限度地提高性能,因此要么增加 html 页面大小,要么增加额外的 http 请求。
我从性能/优化方面问这个问题。
请问对此有何意见?
Possible Duplicate:
When should I use Inline vs. External Javascript?
I have some javascript variables that I use in my javascript (ie. external javascript files)
This javascript variables is page specific and varies per page and user.
Is it better to have these in any other javascript file meaning an extra http request or including it within the html content of the page, bloating the page.
I like separation but want to do all to maximize performance, so either increasing html page size or extra http request.
I ask this question in terms of performance/optimization.
Opinions on this please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过几种不同的方式来做到这一点。一种方法是将数据包含在主脚本中包含的对象中,并在每页上有另一个对象。
或者
你可以做一个配置加载器。
在每个 html 页面中包含
其中将包含类似这样的
内容这可以加载特定页面需要的任何附加数据,如果在一开始就完成,将与大多数相当于 onReady 的库一起工作,例如
要使此方法正常工作,您只需要确保每个文件中的数据在数据包含方面是统一的。
这两种方法应该可以让您在提出解决方案时进行一些思考。
You could do this a couple different ways. One way would be to include the data in an object included with your main script and have another object per page.
Something like
Alternatively you could do a config loader.
in each html page include
Which would contain something like this
This could load any additional data the specific page needs and if done in the very beginning would work along side with mostly libraries equivalent of onReady like
For this method to work you would just need to ensure the data in each file is uniform in the data is contains.
These two methods should give you a bit to think about in coming up with a solution.
您的应用可以有 2 个版本开发和发布。
在您的开发版本中,您并不真正关心脚本的数量,而您的发布版本应该通过将所有脚本合并为一个、缩小它并对其进行压缩来进行优化。
you can have 2 versions of your app dev and release.
In your dev version, you don't really care about the number of scripts, whereas, your release version should be optimized by merging all the scripts in one, minifying it and gzipping it.
如果数据因用户和页面而异,则浏览器无法有效地缓存它们,因此将它们放入外部文件中不会从浏览器缓存中受益,事实上,您必须明确阻止文件被缓存。我建议你把它放在实际的网页中。如果可以的话,将其放在网页 HTML 之后,以便可以先渲染。
If the data varies by user and by page, then they cannot be cached effectively by the browser, so putting them in an external file will not benefit from browser caching and in fact, you'll explicitly have to prevent the file from getting cached. I'd suggest you put it in the actual web page. If you can, put it after the web page HTML so that can render first.