简体   繁体   中英

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.

My problem is that these <script> s get executed multiple times, for example, when I click something, the bounded function get executed several times.

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.

What about a similar solution to the one that's been used in C to prevent header-files to be included multiple times?

For example in the file "example.html" you could wrap your code in an if-statement like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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