javascriptpythonjqueryjquery-eventsmako

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.


Solution

  • 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>