Widget for webmasters in JavaScript and ID-collision
I would like to create a widget that could be placed in another websites/开发者_开发知识库forums.
<script type="text/javascript" src="http://example.com/x.js" />
<div id="myid"></div>
But there is a problem - when someone put on one website two or more such widgets they will not work correctly because of the ID.
What can I do to prevent such situation?
I can't use class because I need to have access to this div from JS. I thought about adding a random-generated number to the end of ID, but there will be still possibility of ID-collision (small, but there will be).
The best way is to be more flexible. So, instead of having a defined html id and force the user to have it, you should provide a way to let user choose its id. And so, a call must be done.
Something like this is cleaner :
<script type="text/javascript" src="http://example.com/x.js"></script>
<script type="text/javascript">
X.callMethod("myId");
</script>
<div id="myid"></div>
This method has two advantages :
- it lets user define its own id
- the user specifies what behavior he wants from your script. With, that, you could add other methods which can be used in same way : user doesn't have the feeling that your code is intrusive, it's him who decides if he wants a feature or not.
You could just include the script... which at processing time generates a div and assigns it a unique ID. (Within that logic, you could check for duplicates)
Presuming you don't expect your widget to be included 1,000's of times... something like this (untested) should work.
var uniqueID;
var foundUniqueID = false;
var idx = 0;
while(foundUniqueID != true){
uniqueID = 'myID_' + idx;
if(document.getElementById(uniqueID)){
idx++;
} else {
foundUniqueID = true;
}
}
//create your DIV with your uniqueID etc.
精彩评论