简体   繁体   English

如何组合我的JavaScript文件并仍然让我的回调等待就绪状态?

[英]How can I combine my JavaScript files and still have my callbacks wait for a ready state?

I have lots of functions and event handlers that are split across multiple javascript files which are included on different pages throughout my site. 我有很多功能和事件处理程序,分为多个javascript文件,这些文件包含在我的网站的不同页面上。

For performance reasons I want to combine all of those files into 1 file that is global across the site. 出于性能原因,我希望将所有这些文件合并到整个站点内的全局文件中。

The problem is I will have event handlers called on elements that won't necessarily exist and same function names. 问题是我将调用不一定存在的元素和相同的函数名称的事件处理程序。

This is an example of a typical javascript file... 这是一个典型的javascript文件的例子......

$(document).ready(function(){
    $('#blah').keypress(function(e){
        if (e.which == 13) {
            checkMap();
            return false;
        }
    });
});

function checkMap() {
    // code
}

function loadMap() {
    // code
}

I would need to seperate this code into an object that is called on that specific page. 我需要将此代码分成一个在该特定页面上调用的对象。

My thoughts are I could re-write it like this: 我的想法是我可以像这样重写它:

(function($) {
    $.homepage = {
        checkMap: function(){
            // code
        },
        loadMap: function(){
            //code  
        }
    };
})(jQuery);

And then on the page that requires it I could call $.homepage.checkMap() etc. 然后在需要它的页面上我可以调用$.homepage.checkMap()等。

But then how would I declare event handlers like document.ready without containing it in it's own function? 但是,我如何声明像document.ready这样的事件处理程序而不将其包含在它自己的函数中?

First of all: Depending on how much code you have, you should consider, if serving all your code in one file is really a good idea. 首先:根据您拥有的代码量,您应该考虑,如果在一个文件中提供所有代码确实是个好主意。 It's okay to save http-requests, but if you load a huge chunk of code, from which you use 5% on a single page, you might be better of by keeping those js files separated (especially in mobile environments!). 保存http请求是可以的,但是如果你加载了一大块代码,你在一个页面上使用5%的代码,你可能会更好地将这些js文件分开(特别是在移动环境中!)。 Remember, you can let the browser cache those files. 请记住,您可以让浏览器缓存这些文件。 Depending on how frequent your code changes, and how much of the source changes, you might want to separate your code into stable core-functionality and additional .js packages for special purposes. 根据代码更改的频率以及源更改的数量,您可能希望将代码分成稳定的核心功能和其他.js软件包以用于特殊目的。 This way you might be better off traffic- and maintainance-wise. 通过这种方式,您可能会更好地避开流量和维护。

Encapsulating your functions into different objects is a good idea to prevent unnecessary function-hoisting and global namespace pollution. 将函数封装到不同的对象中是一个好主意,可以防止不必要的函数提升和全局命名空间污染。

Finally you can prevent calling needless event handlers by either: 最后,您可以通过以下方式阻止调用不必要的事件处理程序

Introducing some kind of pagetype which helps you decide calling only the necessary functions. 引入某种页面类型,帮助您决定只调用必要的函数。

or 要么

checking for the existence of certain elements like this if( $("specialelement").length > 0 ){ callhandlers} 检查是否存在某些元素if( $("specialelement").length > 0 ){ callhandlers}

to speed up your JS, you could use the Google Closure Compiler. 为了加快你的JS,你可以使用Google Closure Compiler。 It minifies and optimizes your code. 它缩小并优化您的代码。

I think that all you need is a namespace for you application. 我认为你需要的只是你的应用程序的命名空间。 A namespace is a simple JSON object that could look like this: 命名空间是一个简单的JSON对象,可能如下所示:

var myApp = {
    homepage : {
      showHeader : function(){},
      hideHeader : function(){},
      animationDelay : 3400,
      start : function(){} // the function that start the entire homepage logic
    },
    about : {
    .... 
    }
}

You can split it in more files: 您可以将其拆分为更多文件:

  1. MyApp will contain the myApp = { } object, maybe with some useful utilities like object.create or what have you. MyApp将包含myApp = {}对象,可能包含一些有用的实用程序,如object.create或者你有什么。
  2. Homepage.js will contain myApp.homepage = { ... } with all the methods of your homepage page. Homepage.js将包含myApp.homepage = {...}以及主页的所有方法。
  3. The list goes on and on with the rest of the pages. 列表与其余页面一起继续。

Think of it as packages. 把它想象成包裹。 You don't need to use $ as the main object. 您不需要使用$作为主要对象。

 <script src="myapp.js"></script>
 <script src="homepage.js"></script>
 <-....->
 <script>
   myApp.homepage.start();
 </script>

Would be the way I would use the homepage object. 将是我使用主页对象的方式。

When compressing with YUI, you should have: 使用YUI进行压缩时,您应该:

<script src="scripts.min.js"></script>
<script>
    myApp.homepage.start();
 </script>

Just to make sure I've understood you correctly, you have one js file with all your code, but you want to still be in control of what is executed on a certain page? 只是为了确保我已经正确理解你,你有一个带有所有代码的js文件,但是你仍想控制在某个页面上执行的内容?

If that is the case, then the Terrific JS framework could interest you. 如果是这种情况,那么Terrific JS框架会让您感兴趣。 It allows you to apply javascript functionality to a module. 它允许您将javascript功能应用于模块。 A module is a component on your webpage, like the navigation, header, a currency converter. 模块是网页上的一个组件,如导航,标题,货币转换器。 Terrific JS scans the dom and executes the js for the modules it finds so you don't have to worry about execution. 很棒的JS扫描dom并为它找到的模块执行js,这样你就不用担心执行了。 Terrific JS requires OOCSS naming conventions to identify modules. 极好的JS需要OOCSS命名约定来识别模块。 It's no quick solution to your problem but it will help if you're willing to take the time. 这不是你的问题的快速解决方案,但如果你愿意花时间,这将有所帮助。 Here are some more links you may find useful: 以下是一些您可能会发现有用的链接:

Hello World Example: http://jsfiddle.net/brunschgi/uzjSM/ Hello World示例: http//jsfiddle.net/brunschgi/uzjSM/

Blogpost on using: http://thomas.junghans.co.za/blog/2011/10/14/using-terrificjs-in-your-website/ Blogpost on using: http ://thomas.junghans.co.za/blog/2011/10/14/using-terrificjs-in-your-website/

I would use something like YUI compressor to merge all files into one min.js file that is minified. 我会使用YUI压缩器之类的东西将所有文件合并到一个缩小的min.js文件中。 If you are looking for performance both merging and minifiying is the way to go. 如果您正在寻找性能,那么合并和微型化都是可行的方法。 http://developer.yahoo.com/yui/compressor/ http://developer.yahoo.com/yui/compressor/

Example: Javascript input files: jquery.js, ads.js support.js 示例:Javascript输入文件:jquery.js,ads.js support.js

run yui with jquery.js, ads.js, support.js output it into min.js 使用jquery.js运行yui,ads.js,support.js将其输出到min.js

Javascript output files: min.js Javascript输出文件:min.js

then use min.js in your html code. 然后在你的HTML代码中使用min.js.

暂无
暂无

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

相关问题 如何将Google自定义搜索与所有已定义好的搜索框结合在一起? - How can I combine the google custom search with my all ready defined search box? 我怎样才能告诉我的 javascript 等到服务器完成? - How can I tell my javascript to wait until the server is done? 我怎么知道React组件已经完成了处理生命周期回调的过程,并准备好在测试中进行交互? - how do I know a react component is done processing lifecycle callbacks and ready for interaction in my test? 在执行我的JavaScript之前,如何等待网页加载完毕并填充所有控件? - How can I wait until a web page has loaded and all controls have been populated before executing my javascript? 如何将两个$(document).ready回调与jQuery结合? - How to combine two $(document).ready callbacks with jQuery? 如何组织我的 javascript 代码而不是嵌套回调? - How do I organize my javascript code instead of nesting callbacks? 我怎样才能在PhantomJS中等待页面准备好? - How can I wait for the page to be ready in PhantomJS? 在javascript认为文档“准备好”之前,如何让我的茉莉花测试装置加载? - How can I get my jasmine tests fixtures to load before the javascript considers the document to be “ready”? 如何让我的 JavaScript 程序的其余部分等待我的 jQuery 动画 - How can I make the rest of my JavaScript Program wait on my jQuery animation 如何让我的 state 在 API 数据触发之前等待它? - How can I get my state to wait on API data before it fires off?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM