Gary Sieling

Testing against multiple jQuery versions

I recently took over maintenance of a jQuery UI plugin that lets you highlight bits of a textarea. Since it’s a UI plugin, most of the testing is done by visual inspection, and supporting different versions of jQuery presents an interesting testing challenge, since jQuery is one of the first things to load on the page.

This is the code that generates the above example:

function runTest() {
  $('#demo1').highlightTextarea({
      words: {
        color: '#ADF0FF',
        words: ['Lorem ipsum','vulputate']
      },
      debug: true
  });
}

It turns out that you can dynamically add scripts to a page, so rather than including jQuery in a script tag, we can import it after the page loads.

Normally you might use “$(document).ready” to run initialization code, but you can use window.onload directly instead:

window.onload = loadJavascript;

Inside the runTests function, you need the ability to append a script, and call a callback once it loads, since this is an asynchronous process.

function appendScript(src, callback) {
  var head = document.getElementsByTagName('head')[0];

  var elt = document.createElement("script");
  elt.type = "text/javascript";
  elt.src = src;

  elt.onload = function() {
    callback();
  }

  head.appendChild(elt);
}

To make the page load correctly, I’ve set this up so you can specify the jQuery version on the URL. Once jQuery loads, it triggers jQuery UI loading, and then finally our own scritpts.

function loadJavascript() {
  // this sets the default
  var jqv = "jquery-1.11.1.min.js";

  try {
    jqv = window.location.search.split('?')[1].split('=')[1];
  } catch (e) {}

  appendScript("http://code.jquery.com/" + jqv,
    function() {
      $('#jqv').val(jqv);

      appendScript(
        "http://code.jquery.com/ui/1.10.4/jquery-ui.min.js",
      function() {
        appendScript("../jquery.highlighttextarea.js",
        runTest
      )})});
}

Once this works, you can add a dropdown with all the jQuery versions you want to support, and set the page to refresh when one is selected:

function setJQuery(newVersion) {
  var jqv = $('#jqv').val();

  window.location = 'index.html?jqv=' + jqv;
}

For completeness, here is the dropdown:


Exit mobile version