捆绑脚本中的$(document).ready() [英] $(document).ready() in a bundled script

查看:33
本文介绍了捆绑脚本中的$(document).ready()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在网络优化方面做了很多工作,我遇到了一个有趣的问题。我想知道是否有人可能知道现有的解决方案。

I've been doing a lot with web optimization recently, and I've come across an interesting problem. I was wondering if anyone might know of an existing solution.

假设您有多个特定于页面的外部.js文件,每个文件都有自己特定的页面
$(document).ready()功能。假设第1页的文档就绪功能将样式应用于正文中的每个< li> ,而第2页中准备好的文档仅为样式< ; input type =button/> s。只是一个简单的例子。

Say you have multiple, page specific external .js files, each with it's own page specific $(document).ready() function. Say the document ready function for page 1 applies a style to every <li> in the body, while the document ready in page 2 only styles <input type="button" />s. Just a simple example.

现在假设您将这两个脚本以及所有库脚本捆绑在一起,以减少页面加载时的http请求数。现在,两个文件准备就绪了,第2页的li将使用仅适用于第1页的代码进行格式化。

Now say you bundle these 2 scripts, along with all your library scripts, to reduce the number of http requests on page load. Now, both document ready's will fire, and the li's on page 2 will be formatted with the code meant only for page 1.

我的问题是这个 - 有没有办法通过jQuery或第三方库将特定文档分配给特定页面,但仍然将它们全部捆绑到一个.js文件中?

My question is this - Is there a way through either jQuery or a third party library to assign a specific document ready to a specific page but still have them all bundled into one .js file?

推荐答案

从架构的角度来看,如果代码块只对一个页面有意义,为什么不将它与该页面捆绑在一起?我知道将所有HTML放在一个地方并将你的javascript放在另一个地方可能看起来更井井有条,但这真的可以节省你的服务器或加快你的用户体验吗?

From an architectural point of view, if the block of code is only meaningful on one page, why shouldn't it be bundled with that page? I know it may seem more "organized" to put all of your HTML in one place and your javascript in another, but is it really saving your server or speeding up your user experience?

当我们减少连接数时会出现捆绑问题,但会增加服务器上的负载,因为我们在组合文件中填充了大量未使用的垃圾。哪个更好地服务1,000个1k文件或100个100k文件。如果您有100个页面,每个页面都有一个唯一的 document.ready ,那么当他们只访问一个页面时,您将为用户添加很多数据。如果用户很可能使用某些捆绑内容,那么这种捆绑的好处实际上才有用。例如Google.com,它们会预先缓存结果页面中所需的实体,因为您在AT google.com的事实意味着您可以非常高度确定地进行搜索。它确实预缓存gmail或谷歌文档。

There comes a point with bundling when we reduce the number of connections, but increase the load on the server because we are stuffing so much unused junk into our combined file. Which is better serving 1,000 1k files or 100 100k files. If you have 100 pages each with a unique document.ready then you're adding a lot of data for a user when they only visit one page. The benefit of such a bundle is really only useful if there is a high probability the user will use some of the bundled content. Example would be Google.com, where they pre-cache entities needed in the results page, since by the very fact you are AT google.com implies with a pretty high degree of certainty you will do a search. It does not pre-cache gmail, or google docs though.

这篇关于捆绑脚本中的$(document).ready()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆