如何使用纯javascript加载jquery,并将加载的jquery用于ajax请求

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

本文关键字:加载 jquery 用于 请求 ajax 何使用 javascript      更新时间:2023-09-26

我不是一个纯粹的javascript程序员,我想利用JQuery。我正在为一个客户做分析,他有很多属于他的客户的子网站。他想做一个报告功能,就像谷歌的分析功能一样,但更多地满足他的定制需求。他创建的网站可能使用不同版本的JQuery,甚至没有使用JQuery。因此,我不能假设他实现的所有网站都在使用JQuery。所以这就是我需要知道的,任何人都可以帮助我建议应该做什么:

  1. 我想创建一个外部javascript来使用纯javascript加载Jquery(托管在谷歌中)。我该怎么做
  2. 只对我的外部javascript文件使用加载的Jquery框架,这样Jquery框架就不会与网站可能调用的任何其他现有版本的Jquery发生冲突。我该怎么做
  3. 有了这个创建的外部javascript,我就可以把它放在所有客户端网站的头部,这样我就可以跟踪分析了

我的客户不想使用谷歌分析,他有自己的理由。希望听到您将如何建议实现您的功能。

由于您的分析将依赖于特定的jQuery版本-您不能使用它所在网站的版本。您需要在自己的脚本中加载所需的jQuery。

jQuery的$.noConflict.可以使用多个版本的jQuery

您的脚本看起来应该有点像以下内容:

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);

对于$.noConflict的其他用途,请签出jQuery文档。

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