How to make sure that the script runs once and only once

I am writing a widget template that will be included on the page where it is installed.

You can install several identical widgets on the same page, so my template can be included several times.

Now I have written some JavaScript to initialize the widget, you know, clicks and freezes.

My problem is that these <script> are executed several times, for example, when I press something, the limited function is executed several times.

What is the best way to solve this problem?

EDIT: By the way, I use the Mako template engine, and I tried to use the variable c to store the boolean flag, but it seems that c overridden every time.

+4
source share
1 answer

What about a similar solution for the one used in C to prevent header files from being included multiple times?

For example, in the file "example.html" you can wrap your code in an if-statement as follows:

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

Source: https://habr.com/ru/post/1383600/


All Articles