I have a javascript widget (a piece of embedded JS and HTML code) that's embedded on other sites. What should I do to make sure it's variable names don't clash with the hosting page variables?
I'd like this widget to be "inlined" meaning on the same page as the hosting page, not in an iframe, what's the best way to avoid name clashes with the hosting page or clashes with other widgets?
Name clashes can happen in several ways:
- Javascript variable names
- Javascript function names
- DOM elements identifiers
- CSS class names
- maybe more...
I can think of several ways to avoid name clashes, but I was wondering if there's a best-practice or other general recommendations. So here's my 2c:
- Just use long and try-to-be-unique names. That's ugly and not full-proof, but is simple in concept.
- Use an iframe. But as mentioned, I don't want to use an iframe for several reasons. I want the widget to inherit style attributes from the page (such as default font and background color) and most importantly, I don't know how large the widget is going to be. It depends on real-time data and may be of any size.
- Use anonymous functions for better scoping, e.g. (function(){my code here})(). This solution, while elegant, still does not work for me b/c first, it only solves the JS name clashed but not the DOM ID ones or CSS class names and second, I also use jsonp for which I need to provide a callback function name, which eventually needs to be in the global scope, so it cannot be nested in the anonymous function scope.
- Create a namespace mechanism in javascript that'll provide uniqueness of JS variables and function. Something of the style window['my_app'][variable_name] or window['my_app']function_name. That's a bit ugly as well, but at least I have control over the namespace and can generate guarantied to be unique namespaces.
Thanks!