代码结构的 JavaScript 习惯用法

发布于 2024-07-12 07:34:43 字数 466 浏览 5 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我要还你自由 2024-07-19 07:34:43
var _ow = _ow || { Auth: ... };

如果已经定义,则不会再次定义。

var _ow = _ow || { Auth: ... };

if its already defined then it wont be defined again.

疾风者 2024-07-19 07:34:43

您熟悉 Crockford 的 Javascript 模块模式吗?

关于如何防止覆盖命名空间的略有不同:

var _ow;
if(!_ow) _ow = {};

Are you familiar with Crockford's Javascript Module Pattern?

A slight variation on how to prevent overwriting the namespace:

var _ow;
if(!_ow) _ow = {};
-柠檬树下少年和吉他 2024-07-19 07:34:43

虽然您正在做的事情在技术上可行,但效率很低,因为即使您的代码只运行一次,它最终也会在某些浏览器上被解析多次(这与通过网络下载文件不同,并且不能被缓存)。

最好确保脚本只包含一次。 对于所有重复的功能,您可以公开一个函数,以便在需要时调用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文