The Orca
The Orca

Reputation: 1250

load qUnit asynchronously

I am trying to load QUnit in js but the addevent function in QUnit.js is never fired, and it's just not working:

var appendQUnit = document.createElement('script'); 
appendQUnit.src = 'js/utility/qunit/qunit.js';
appendQUnit.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(appendQUnit); 

Upvotes: 3

Views: 714

Answers (3)

Paul Sweatte
Paul Sweatte

Reputation: 24637

Use the following in your code or as a bookmarklet:

Code

void(function foo()
  {
  /* get head element */
  var head=document.getElementsByTagName("head")[0];

  /* create script and link elements */
  var qUnitJS = document.createElement("script");
  var qUnitCSS = document.createElement("link");

  /* link rel and type attributes required for lazy loading */
  qUnitCSS.rel="stylesheet";
  qUnitCSS.type="text/css";

  /* define script src attribute to lazy load */
  qUnitJS.src = "http://qunitjs.com/resources/qunit.js";

  /* append script and link elements */
  head.appendChild(qUnitJS);
  head.appendChild(qUnitCSS);

  /* define link href after DOM insertion to lazy load */
  qUnitCSS.href="http://qunitjs.com/resources/qunit.css";

  /* call tests after QUnit loads */
  qUnitJS.onload = function () {};
  }() )

Bookmarklet

javascript:void(function foo(){var head=document.getElementsByTagName("head")[0]; var qUnitJS = document.createElement("script"); var qUnitCSS = document.createElement("link"); qUnitCSS.rel="stylesheet"; qUnitCSS.type="text/css"; qUnitJS.src = "http://qunitjs.com/resources/qunit.js"; head.appendChild(qUnitJS); head.appendChild(qUnitCSS); qUnitCSS.href="http://qunitjs.com/resources/qunit.css"; qUnitJS.onload = function () {};}() )

In Firefox, set security.mixed_content.block_active_content to false in about:config to run the mixed active content as a bookmarklet.

References

Upvotes: 0

Alex Pacurar
Alex Pacurar

Reputation: 5871

You can use the jquery's getScript, example:

$.getScript('js/utility/qunit/qunit.js', function() {
    // here you can handle the qunit code
});

because the browser will always load javascript files in async mode, you will need some callback to place your code that handles the new loaded js code.

Upvotes: 2

evpozdniakov
evpozdniakov

Reputation: 61

You might need also to call QUnit.load() in order to initialize QUnit:

$.getScript('js/utility/qunit/qunit.js', function(){
QUnit.load();
// here you can handle the qunit code
});

Upvotes: 6

Related Questions