简体   繁体   English

如何确保脚本只运行一次

[英]How to make sure a script runs once and only once

I am writing a widget template, which will be included in a page where it is installed. 我正在编写一个小部件模板,它将包含在安装它的页面中。

One may install several of the same kind of widget in one page, so my template may get included several times. 可以在一个页面中安装几个相同类型的小部件,因此我的模板可能会被包含多次。

Now I have written some JavaScript to initialize the widget, you know, the clickings and hoverings. 现在我已经写了一些JavaScript来初始化小部件,你知道,点击和悬停。

My problem is that these <script> s get executed multiple times, for example, when I click something, the bounded function get executed several times. 我的问题是这些<script>被多次执行,例如,当我点击某些东西时,有界函数会多次执行。

What is the best way to solve this problem? 解决这个问题的最佳方法是什么?

EDIT: By the way, I am using the Mako template engine, and I've tried using the c variable to store a boolean flag, but it seems that the c get overridden every time. 编辑:顺便说一下,我正在使用Mako模板引擎,并且我尝试使用c变量来存储布尔标志,但似乎每次都会覆盖c

What about a similar solution to the one that's been used in C to prevent header-files to be included multiple times? 如何在C中使用的类似解决方案来防止多次包含头文件?

For example in the file "example.html" you could wrap your code in an if-statement like this: 例如,在文件“example.html”中,您可以将代码包装在if语句中,如下所示:

<script type=text/javascript>
    if (!window._EXAMPLE_HTML_) {
        window._EXAMPLE_HTML_ = true;
        // your code goes here
    }
</script>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM