How can I create an external javascript code for users like the Google Analytics JS Code?
I'm starting a project where I need to create an external javascript code for users to input into their website (like they do with the Google Analytics Snippet). I know a little bit of j开发者_运维问答avascript by way of JQuery, but I'm not sure how I would begin.
I'm nervous I'm using the wrong terminology to find what I'm looking for.
From a technical standpoint, this is accomplished the same was as including a static JS file in your own website - through the use of a script tag. The only difference being that the source for your JS file is on a different domain than your website.
As for the actual contents of the JS file, that is much harder to give advice on since your question is so oblique. The only thing I can suggest is that
1) You cannot depend on the site including any dependent libraries, such as jQuery
2) Pollute the global namespace as little as possible. Ideally it will only be a single object in the global namespace, with all your code living underneath.
Just provide them a js file to include in theur headers. Be sure to not modify the global scop because you dont know what they are doing. Usually, this is ensured using a closure :
(function(){
// Put your code here
window.yourLibName = someObject;
})();
The only code they can use in the global scope is yourLibName, everything else si kept within your colsure.
Then, you can provide them a code sample to call your tool from their webpage. Something like :
<script type="text/javascript"><!--
yourLibName(someParameters);
//-->
</script>
This method will lead to something clean and usable on most websites.
Also, avoid using libraries like jQuery in such a solution, as it has a risk of messing up the client's javascript, especially if he is using a different version of jQuery or another lib like mootoools.
Some basic principle
make your code as small as possible.
Do not depend on library like Jquery. It would make conflict on third party's site easily.
make your script load asynchronous
leave some interface so others can do sth. custom setting upon your code.
Do not add too many global variables. Try to use namespace to write your code.
精彩评论