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 guaranteed to be unique namespaces.
Javascript namespaces:
http://www.codeproject.com/KB/scripting/jsnamespaces.aspx
It is heavily used in several javascript frameworks/libraries, such as YUI:
http://developer.yahoo.com/yui/yahoo/
In my previous project I had a widget that was embedded on other sites, and to prevent name conflicts I prefixed all names that would be used in the embedding sites with a two letter prefix (I got the idea from Objective C, where all classes start with a prefix like NS...).
Of course I also used namespaces (e.g. var Foo = { bar: function() { ... }}) and "classes" (using John Resig's class implementation), because I use them regardless if I have a widget or not, but the names of the namespaces, classes and global variables or functions were prefixed - e.g. HMWidget, HMClass, hmDoSomething(), etc.
Regarding DOM IDs and CSS classes - first, I had to get rid of most IDs because of the possibility of having multiple widgets from my service on the same site. So the only IDs that were left were something like "widget_12345" to tell the widgets apart. The rest of the elements were identified by CSS classes, and all CSS declarations were done in relation to the main widget container (e.g. ".my_widget .left_column" instead of just ".left_column").
Related
For a single-page app: I want each of my DOM nodes to have a reference to a single (in-browser) domain object. Is it OK to just store a direct reference like this:
var myDomainObject = ...;
var DOMNode = document.getElementById("myId");
DOMNode.domain_object = myDomainObject;
Is this safe, repeatable? Can the browser do mysterious things with added-on JavaScript properties?
Thanks.
From an experiential standpoint: I've attached data directly to nodes without issue and never had a problem. From a specification standpoint, my interpretation is that doing so is not necessarily recommended, but is safe to the extent that the custom attributes don't conflict anything else.
In Common Infrastructure - Extensibility, the recommendation for authors (that's you) is to use only [data-*] attributes:
Authors can include data for inline client-side scripts or server-side
site-wide scripts to process using the data-*="" attributes. These are
guaranteed to never be touched by browsers, and allow scripts to
include data on HTML elements that scripts can then look for and
process.
And the requirement for a valid user-agent is to leave anything in the DOM it doesn't recognize.
User agents must treat elements and attributes that they do not
understand as semantically neutral; leaving them in the DOM (for DOM
processors), and styling them according to CSS (for CSS processors),
but not inferring any meaning from them.
So, my suggestion, along the same line as the W3C's aim of avoiding conflicts, is to create objects that refer to DOM elements. But, if you "must" tag weird things onto the DOM, rest assured that user agents are required to leave it there. But if you really must, it may be wise to use those data-* attributes!
(I personally don't use them and tend to slap objects and values onto whatever's most convenient at the time. But, I may be jaded by about 15 years of hacks and "feature detection" for the non-compliance of the user agents. Even now, I don't think IE supports the data-* standard ... )
I've done it before to store custom events and it works fine in every browser I tried but yeah, it's dangerous I'd say, only if there are no other alternatives and you must pass this info with the element.
At least, ideally, create your own namespace to not pollute the already polluted object:
var myDomainObject = ...;
var DOMNode = document.getElementById("myId");
DOMNode.My = {};
DOMNode.My.domain_object = myDomainObject;
Edit: Just wanted to see how many methods and properties a regular div might have, and it has 136 (in Chrome). http://jsbin.com/abecaq/1/edit
While it wouldn't cause any issues on a small site, I would avoid doing this for a few reasons...
You are opening yourself up to memory leaks by linking references to many different JS objects
Any new DOM nodes would have to have this link attached
I would recommend utilizing a global variable or ideally a variable at the highest necessary scope that can be referenced whenever necessary.
I have a page that could contain a different inner page at any specific time.
Each inner page needs a specific js file, that is being loaded dynamically using the Headjs.
To avoid collisions (of methods and object names), I would like to unload the old js file before loading a new one.
Does anyone know how to do it, or if it is even possible? Thanks!
No. Theoretically there's nothing like "unload" javascript file. Once its loaded its there all the time.
But there might be other tricks to avoid "collision", mainly clean code. some examples for your case would be
1- Usage of namespaces
2- avoid global variables
3- define everything within a scope and understand scopes
4- Use understandable descriptive variable names, avoid variables named s,i,j, etc.. unless you are used to that and know what're doing. Also be aware since javascript files are loaded when a page is requested, so it causes extra traffic to use huge large names for variables and classes.
Lets say you have functions with same name but live in different scopes/namespace
Example:
var myclass;
if (something) myclass = Obj1;
else if (somethingelse) myclass = Obj2;
myclass.func();
so here you go, two functions with the same name, but live in different classes.and so you can switch between different implementations
Hope this helps
I've been using this kind of programming pattern lately in order to group logically related functions:
FruitMethods = {
url: "some/path/to/something.durk",
get: function(data) {$.ajax(url, data)},
delete: function(something) { some more function stuff....}
}
You get the picture right? It doesn't seem to really meet the definition of a Class... or does it? A Mixin? Something else? Javascript Object Full Of Functions And Maybe A Variable? JOFOFAMAV?
My vote if for JOFOFAMAV.
PS: Feel free to also chime in with your thoughts on whether or not this is a good practice.
Functionally, it's an object with properties. So, then your question becomes more about what common name would one call it.
Because it has no instance data and doesn't appear like one will be creating new instances of it (e.g. like a class), then it is most like a namespace which is just a named wrapper for a bunch of properties where properties can be any sort of data or functions.
Namespace objects are useful for a bunch of reasons:
Limiting the use of the top level, global namespace thus lowering the chance of a name conflict with other scripts.
An organizational structure/convention for collecting a group of related data or functions.
A hierarchical scheme that makes it easier for categorizing or organizing methods and/or data and referring to them with a simple scheme of category.method like Fruit.get()
I would call that a namespace.
That's a form of singleton - which is basically an object without an external definition: you don't have a 'class' definition and then create instances of that class.
One thing to know about this type of structure is that all of the methods of the object are public ( that may or may not be a problem).
I've been told that it's standard practice to prefix class names on HTML elements with "jq" or "js" so that the designer doesn't conflict with the developer.
I've been around a little and I've never seen this done and personally feel this creates an artificial and unhelpful divide between design and code.
The question is whether this is indeed standard practice, and moreover, I would like references to articles explaining why this is done (what problem does it solve).
I'm the front-end developer at my organisation and as such am responsible for the CSS. I create all the required classes for layout and UI, as well as periodically tidying up unused styles and mark-up.
Our developers never need to add classes for presentation, but they do occasionally add classes for Javascript. In these instances I have asked them to prepend their classes with js-.
This simply helps me identify classes that are not used for presentation, but are still required for functionality. My other class names are all descriptive of the content.
Before we introduced this it was much harder to keep the mark-up tidy (by removing unused classes) as classes could seem redundant (with no references in the stylesheets), but were still used.
I've not come across any documentation saying this is a bad idea. It works for us, so is simply a matter of personal preference.
This sounds like an old fashioned convention for me especially in context with html/javscript/css.
Classes should only be used for layout reasons. If there are classes anyway, defined by a designer, then they can and should be used by developers. Values for pure programm controls should be defined using custom attributes (http://www.javascriptkit.com/dhtmltutors/customattributes.shtml). This practice together with detailed and well-thought-out naming conventions mostly avoid problems.
It also sounds like classes would have to be assigned to elements twice often with this prefix pratice. One more reason to ask how a practice like that can be a good or even standard one.
Edit:
Prefixes can be useful inside plugins for e.g. javascript libraries of course to avoid class conflicts!
It's not a general standard practice, but it may be a standard practive within a specific organisation.
Using prefixes to specify usage of an identifier is called hungarian notation. It's mostly used to specify data types in script languages without strict typing, but the original intention was just to specify any aspect that was crucial to the use of the identifier.
Using prefixes like that can be useful to make sure that classes intended for design doesn't conflict with classes intended for program control. It's however not dependant on who is creating the class, but how the class is used. If a developer creates a script that adds a class to elements to change their appearence, the class is used for design so it should not be prefixed as a program control class name. A class name used for program control would only be used for that, and have no visual style applied to it.
As with most programming practices, it's more important that you pick a standard and stick to it, than picking the standard that is absolutely best.
Not only is it not standard practice (except, presumably, in your organisation), but the W3C advises against it. Class names should be used to further describe the contents of semantic HTML tags, rather than as reference points for design or development.
I would expect well-structure HTML pages to have consistent classes for similar content types which would be perfectly suitable for JavaScript usage.
A designer who cannot write HTML correctly, remembering that the HTML markup is supposed to describe the content not style it, should not be writing HTML IMO.
I've certainly not heard of this as a 'standard' practice. Reading guidelines and articles, I have never seen a prefix infront of a class.
However, it might be handy prefixing a class name if you were going to use that class with jQuery. It will be easier to identify and also it would let others know that it used by a function.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
I use only classes and never use IDs.
Many people like to use IDs for different reasons.
I've seen many questions regarding IDs vs classes on stackoverflow, but no one addressed pure code organization point of view disregarding compatibility and runtime performance.
From code organization point of view, I think that using IDs is bad just like using global variables in Visual Basic code.
One reason is that IDs have to be unique which introduces unnecessary and bad dependency between different independent parts of your code (controlling different parts of HTML DOM tree).
Another reason is that making new class names is actually easier than ID names because with IDs you have to worry about global scope and with class names you need to worry only about uniqueness in local scope, same benefit as with local variables.
Most people will argue that performance of addressing by ID is better than by class and I will agree with that. But as browsers become more advanced with native implementations of CSS addressing from javascript and computers become faster, performance becomes less and less important. So let's disregard it and concentrate only on organization of code in context of current question.
This discussion started here, but my potentially wrong advice generates negative points and became too big to keep in comments, so here I try to convert it into something positive and manageable.
One visible point in favor of IDs is to use them as a tool of rule prioritization because priority of #name is higher than priority of .name.
My response: using IDs to raise priorities is bad hack, it's cleaner and there is more freedom if you use additional root elements inserted between body and other levels of tree, for example priority of body div div span.class1{} is higher than body div span.class1{} is higher than body span.class1{} is higher than span.class1{}. Another tool to use for that purpose is !important.
Some may argue that using more root elements means more difficulties when the page structure changes, but I don't think this is the case because you never have to put anything between body and designated for prioritization divs. Those divs can always stay below body and above all other content.
Another interesting association was brought about pointers and that IDs are not bad because pointers are not bad.
My response: pointers are bad if you hardcode absolute memory address in your code. Using relative pointers is always better (examples: using segments(CS,DS,SS,ES) in 8086 CPU; relative variable and method addresses generated by compilers). If we consider DOM tree as memory and compare using ID to using class then #name represents absolute memory address, but div.tab1 .name represents relative address (relative to div.tab1).
Another supporting point that I've seen for IDs is that elements with IDs are more easily available in javascript as becoming global properties. My response: again, this is like saying that global variables in Visual Basic are more conveniently available. The problem is that you can't keep large enough global (or any other) namespace in order without introducing naming hierarchy like level1_level2_name, which is just a hack to replace one namespace mechanism with another. DOM tree is convenient enough to organize namespaces, why disregard it ?
Namespace simulation inside IDs using underscore is bad because you can't establish naming context and will have to duplicate all paths everywhere in your code. That practically means that you won't be able to use CSS preprocessors that fix inability of CSS to use contexts.
quick answer: its a best practice, if you have only one instance of something and you only want one instance if it, use an ID to define that there should only be one instance of it.
This is like the difference between constant variables vs regular variables. You can use a regular variable to be a constant variable, but its better to define it as such if that is what its intended to be.
It lets fellow programmers (and yourself) know more information about the object.
I agree with you in general: Classes are much cleaner to use; you can create "namespaces" and clean cascades with them; and they can be combined: class='class1 class2'.
IDs still have their place when you're addressing really unique elements on the page, especially when addressing an element that is going to be changed in JavaScript later (e.g. a hidden overlay.)
I look at classes and ids the same way I look at a (programming) class versus an object. An object is one, specific instance of a class. I want all my classes to share a certain number of behaviors, but an individual object may have its own unique properties. CSS classes are for applying properties to broad groups of similar items, ids are for specific items and the specificity hierarchy reflects that.
To invert your question, why use classes at all when you could achieve the same effects with very specific tag selectors? For ease of use, repeatability and clarity of intent.
For me, I like using IDs on HTML elements that are absolutely unique, and classes on things that are possibly non-unique (regardless of whether or not they are).
For example, I would use <div id="header"> because there can only be one header. But I would use <div class="profile"> if there could conceivably be more than one on the page (even if there is only one). This makes the CSS a little easier for me to understand.
"DOM tree is convenient enough to organize namespaces, why disregard it ?"
Because the DOM can change due to AJAX or other javascripty-goodness.
I like #ocdcoder 's constant/variable analogy. Sometimes you want to refer to exactly that particular element. Having to adhere to a strict DOM namespace is a straightjacket that doesn't help maintenance at all, imho.
I think the discussion is incomplete without addressing the underlying reason for using classes and IDs. Saying that either should be used in every situation does not work well generally and historically.
The original purpose of classes was to attach presentation to the document, or introduce style as a separate concern than the structure of the document itself. Please correct me if I am wrong, but I think you are trying to address the problem of attaching semantic information to the elements rather than just style. If that is indeed the case, then classes serve two purposes for us - controlling presentation, and acting and semantic tags. IDs serve the purpose of acting as a unique semantic tag.
XML is highly extensible and allows namespaces which was supposed to be used in XHTML documents to assign meaning to a document as authors saw fit. But there were none in HTML and maybe it was browser incompatibilities or the non ease of use (as Tom mentioned), but most web pages and applications did not take the path of using namespaces in XHTML.
Surely the HTML spec authors saw the glaring need for attaching semantic data to HTML documents and introduced the data- attributes in HTML5 that could be assigned to any element. I would argue that if it's semantic meaning that you are concerned with, this is absolutely the best approach so far, but again browser incompatibilities have always had a major role in determining which spec becomes more commonplace and I hope IE does not have their say this time.
Using an id attribute allows you to link to an element E.g. if you’ve got this HTML:
<div id="log-in">
you can link to the log in section of the page using href="#log-in".
You’re quite right that classes are usually the most convenient and appropriate way to identify page components. But assuming that you’ve got an element that only appears once per page, and assuming you can give it an appropriate name or generate one, I don’t think you’re likely to run into problems using an id for it.