如何更加模块化地编写 jQuery 代码?
我正在使用框架 (Django),并且在编写 HTML 方面有很大的灵活性。我一直认为我编写 jQuery 的方式可能会更好。
以此为例:大多数情况下,我们网站上出现提交按钮的任何地方,我们都会将其转换为更漂亮的按钮(采用原始值和行为并基本上替换它)。这只是一个示例,但在很多用例中,我在网站上放置了 html 片段,而总体结构不知道页面上需要由 Javascript 操作的内容。所以问题分为两部分:在 100 个页面上执行仅在 50 个页面上使用的内容是否有效(首先搜索包装集的 jQuery 插件),如果我想真正使用我的 jQuery 进行模块化方法,将如何我去办事吗?
I'm using a framework (Django) and I have a lot of flexibility in how I write HTML. I keep thinking that the way I'm writing jQuery could be better.
Take this for example: mostly anywhere a submit button appears on our site, we convert it into a prettier button (takes the original values and behavior and replaces it basically). This is just an example but there are a lot of use cases where I have snippets of html placed on the site and the overarching structure has no idea what is on the page that need to be manipulated by Javascript. So 2 part question: is it efficient to execute something on 100 pages that will only be used on 50 (jQuery plugin that searches for a wrapped set first), and if I wanted to just really have a modular approach with my jQuery, how would I go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您问题中的根本问题是关于模块化编程。我目前正在学习 Douglas Crockford 的“JavaScript:优秀部分”。
来自这本书:
因此,正如在 javascript 中所有函数都是对象一样,您可以使用对象字面量符号以这种方式将顶级结构定义为模块:
实际上是我在 wordpress/joomla 等中构建所有 jquery 代码的方法,我们在其中共享与很多外国人的javascript代码相同的范围。
If the fundamental concern in your question is about Modular programming. I am currently studying Douglas Crockford's "JavaScript: The Good Parts".
From this book:
So, as in javascript all functions are objects, you can use object literal notation to define top-level structures as modules in this way:
Actually is my way to structure all my jquery code inside wordpress/joomla, etc., where we share the same scope with a lot of foreigner javascript code.
通过适当的缓存,使用单个缩小的 .js 文件肯定会更有效。它只会加载一次,并且每页只会有 1 次调用。如果你模块化你的代码,你最终会发出更多的请求,同时不会节省任何额外的 js 时间,因为无论如何它都会被缓存。
With proper caching, it is definitely more efficient to have a single minified .js file. It will only be loaded once and there will only be 1 call per page. If you modularize your code, you will end up doing more requests, while not saving any time dling the extra js, as it will be cached anyway.
这就是您所需要的: http://dvcs.w3 .org/hg/webcomponents/raw-file/tip/explainer/index.html 。但这仍然是非常实验性的。现在看看谷歌关闭工具。
This is what you need : http://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html . But it is still very experimental. For now look at the google closure tools.