【问题标题】:load qUnit asynchronously异步加载 qUnit
【发布时间】:2010-05-20 03:02:38
【问题描述】:

我正在尝试在 js 中加载 QUnit,但 QUnit.js 中的 addevent 函数从未被触发,它只是无法正常工作:

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

【问题讨论】:

  • 我能问一下你为什么要这样加载 qunit 吗?

标签: javascript jquery asynchronous dependency-injection qunit


【解决方案1】:

您可能还需要调用 QUnit.load() 来初始化 QUnit:

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

【讨论】:

  • +1 load() 没有记录在当前版本中,所以我不完全确定信任它的程度,但经过几个小时的尝试一切我能找到的,这是唯一的对我来说,让 QUnit 和 Requirejs 很好地结合在一起的东西。
  • 谢谢。我正在使用QUnit.init(); QUnit.start();。我得到了测试,但没有 userAgent 或选项。
【解决方案2】:

可以使用jquery的getScript,例子:

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

因为浏览器总是以异步模式加载 javascript 文件,所以您需要一些回调来放置处理新加载的 js 代码的代码。

【讨论】:

    【解决方案3】:

    在您的代码中或作为书签使用以下内容:

    代码

    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 () {};
      }() )
    

    书签

    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 () {};}() )

    在 Firefox 中,将 about:config 中的 security.mixed_content.block_active_content 设置为 false 以将 mixed active content 作为书签运行。

    参考文献

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      相关资源
      最近更新 更多