madi
madi

Reputation: 5662

How to load jquery using pure javascript and use the loaded jquery for ajax request

I am not a pure javascript coder and I want to leverage on JQuery. I am doing an analytic for a client who has many sub websites that belongs to his clients. He wants to do a reporting feature just like how Google analytic functions but more to his customized needs. The websites that he has created may be using different versions of JQuery or not even be using JQuery. Thus, I can't assume that all websites that he has implemented is using JQuery. So this is what I need to know and anyone can help me advise of what should be done:

  1. I want to create an external javascript to load Jquery (hosted in google) using pure javascript. How can i do this?
  2. Use the loaded Jquery framework only for my external javascript file so that the JQuery framework does not conflict with any other existing versions of Jquery that might be called by a website. How can i do this?
  3. With this external javascript created can be den be put in the head section of all my client websites so that I can track for analytics.

My client does not want to use google analytics and he has his reasons. Hope to hear how you will suggest implement your feature.

Upvotes: 1

Views: 1419

Answers (2)

PsyBurn
PsyBurn

Reputation: 231

Since your analytic will be dependant on a specific jQuery version - you can't use the one from the site it's included on. You will want to load the wanted jQuery in your own script.

Multiple version of jQuery can be used with jQuery's $.noConflict.

Your script should look somewhat like the following:

var script = document.createElement('script');
script.type = 'text/javascript';
//the url of the needed jquery
script.src = '//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js';
script.onload = script.onreadystatechange = function() { 
  var rs = this.readyState; 
  if (rs) {
    if ((rs != 'complete') && (rs != 'loaded')) {
      return;
    }
  }
  //after loading the jQuery - relinquish jQuery's control of the $ variable.
  var myQuery = $.noConflict(true);
  // alias loaded jQuery to a $ within the functions scope 
  myQuery(document).ready(function($) {
    // code here normally with the loaded jQuery using the $ variable
  });
}
//append the script into the document head
document.getElementsByTagName('head')[0].appendChild(script);

For other uses of $.noConflict checkout jQuery docs.

Upvotes: 2

Nikolay Ayrapetov
Nikolay Ayrapetov

Reputation: 304

window.jQuery || document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"><\/script>')

Upvotes: -1

Related Questions