How to use jquery inside javascript api?

I am looking to develop a javascript web service that a website can include in a single line of code, similar to how Google Analytics is used. I would like to use jQuery in my javascript code, but I do not want it to contradict any js libraries that may already be present on the hosting web page.

Basically, inside my main javascript file that the end user will include in his webpage, I would like to do something like:

document.write('<script type="text/javascript" ' + 'src="http://mydomain.com/js/jquery-1.4.2.min.js"></script>'); 

... make jquery available in my code library. I am wondering if this is the right way to use jquery in an api java script, or if there are more considerations to be made. I would appreciate any examples or articles anyone can offer.

+4
source share
3 answers

See: How to create a web widget (using jQuery) tutorial from Alex Marandon. This explains the many approaches to what you are trying to do.

+1
source
+1
source

While I made the booklet generator a shameless plugin that included jQuery.

You can check the executable code , in particular this snippet:

 if (!window.zbooks) { //if zbooks hasn't been set, initialize it //s used for the Script element var s = document.createElement('script'); //r used for the Ready state var r = false; //set the script to the latest version of jQuery s.setAttribute('src', 'http://code.jquery.com/jquery-latest.min.js'); //set the load/readystate events s.onload = s.onreadystatechange = function() { /** * LOAD/READYSTATE LOGIC * execute if the script hasn't been ready yet and: * - the ready state isn't set * - the ready state is complete * - note: readyState == 'loaded' executes before the script gets called so * we skip this event because it wouldn't have loaded the init event yet. */ if ( !r && (!this.readyState || this.readyState == 'complete' ) ) { //set the ready flag to true to keep the event from initializing again r = true; //prevent jQuery conflicts by placing jQuery in the zbooks object window.zbooks = {'jQuery':jQuery.noConflict()}; //make a new zbook window.zbooks[n] = new zbooks(c); } }; //append the jQuery script to the body b.appendChild(s); } 
0
source

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


All Articles