代码结构的 JavaScript 习惯用法
我的 javascript 多次包含在 script 标记中,如下所示:
<script src="code.js></script>
<script src="code.js></script>
<script src="code.js></script>
现在我在 code.js 中有此代码,使我的代码仅运行一次而不会覆盖我的命名空间:
if(typeof _ow == "undefined" ){
_ow = {};
// code in here will only run once
_ow.Auth = (function(){
})();
_ow.Template = (function(){
})();
}
是否有更好的结构用于使我的代码只运行一次?
My javascript gets included multiple times with the script tag, like so:
<script src="code.js></script>
<script src="code.js></script>
<script src="code.js></script>
Right now I have this code inside code.js to make my code run only once without overwriting my namespaces:
if(typeof _ow == "undefined" ){
_ow = {};
// code in here will only run once
_ow.Auth = (function(){
})();
_ow.Template = (function(){
})();
}
Is there any better structure I could use to make my code only run once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果已经定义,则不会再次定义。
if its already defined then it wont be defined again.
您熟悉 Crockford 的 Javascript 模块模式吗?
关于如何防止覆盖命名空间的略有不同:
Are you familiar with Crockford's Javascript Module Pattern?
A slight variation on how to prevent overwriting the namespace:
虽然您正在做的事情在技术上可行,但效率很低,因为即使您的代码只运行一次,它最终也会在某些浏览器上被解析多次(这与通过网络下载文件不同,并且不能被缓存)。
最好确保脚本只包含一次。 对于所有重复的功能,您可以公开一个函数,以便在需要时调用。
While what you are doing will technically work, it is inefficient, because even though your code only gets run once, it does end up being parsed a number of times on some browsers (this is different than downloading a file via the network, and cannot be cached).
It is best to ensure that the script only gets included once. For all the repeated functionality you can expose a function to be called whenever needed.