在构建站点时,作为个人偏好,我喜欢创建一个主javascript文件,该文件的顶部有window.load和window.ready。
作为一种可读性的方法,我倾向于将这些函数中的任何逻辑重构到它们自己的函数中,并且通常只在元素存在于DOM中时才运行这些函数。
在大多数情况下,我觉得这比将所有东西直接转储到load/ready函数要干净,但是随着我的javascript技能的提高,我开始编写更多的匿名函数,而且随着document部分开始变长,我的代码看起来有点混乱。
就这个问题而言,我想知道:
我提供了一个例子,说明我的文件看起来是什么样的。
$(window).load(function() {
if ( $('#el-1').length !== 0 ) { $('#el-1').addClass('add'); }
});
$(document).ready(function() {
if ( $('#el-2').length !== 0 ) { new my_plugin('#el-2'); }
if ( $('#el-3').length !== 0 ) { simple_function(); }
/* This starts to get messy when there's multiple checks,
// longer function names, and different libraries etc.
*/
});
var simple_function = function() {
//do the short thing
};
;(function( window, $ ) {
'use strict';
function my_plugin( el, options ) {
this.el = $(el);
this.options = $.extend( this.defaults, options );
this._init();
}
my_plugin.prototype = {
defaults : {
something: 'something'
},
_init : function() {
// do the things
}
_internalFunction: function() {
// do the things
},
externalFunction: function() {
// do the things
}
}
window.my_plugin = my_plugin;
})( window , jQuery );发布于 2016-03-31 21:56:40
你的方法在技术上已经是正确的。其他一切都取决于您使用的框架、技术和加载方法等。否则,一切都是关于意见和惯例的。如果你在一家规定了非常严格的代码编写规则的公司工作,那么无论如何你都必须遵守这些规则。
当您将代码拆分为多个文件时,您可以使用模块定义格式/模式(如requirejs或commonjs )来更好地管理依赖项和模块。
如果您正在讨论javascript和jquery的最佳实践和设计模式,那么以下资源可能会有所帮助:
JQuery样板:本网站展示了许多例子,并解释了它们如何以及为什么被认为是最佳实践。(帮了我很多)
学习JavaScript设计模式:这是一本免费的在线书,作者是Google工程师Addy Osmani,他也是jqueryboilerplate.com的开发人员之一。
编辑:如果你想更好地构造你的代码,这本关于设计模式的书尤其有帮助。
https://stackoverflow.com/questions/36343848
复制相似问题