【问题标题】:How do you dynamically load a js file with attributes and execute a callback on load?如何动态加载带有属性的 js 文件并在加载时执行回调?
【发布时间】:2011-12-23 00:51:17
【问题描述】:

我的尝试

jQuery 的$.getScript 做了其中两件事,但我不知道如何为它添加到页面的标签添加属性。

我也试过这个(注意:它在 Coffeescript 中):

$("<script>", {src: alohaScriptUrl, "data-aloha-plugins": alohaPlugins})
  .bind("load ready", onAlohaLoad) // also tried: .load(onAlohaLoad)
  .appendTo("head")

通过上述方式,文件加载并且有适当的标签,但永远不会调用onAlohaLoad。

如何实现这三者 - 动态加载文件、在脚本标签中具有属性以及在加载时执行回调?

这是解释我想做什么的咖啡脚本,但它不起作用:

$ ->
  onAlohaLoad = ->
    console.log("aloha loaded")

  if localStorage["isAdmin"] == "true"
    alohaScriptUrl = "/plugins/alohaeditor-0.20.0-RC9/lib/aloha.js"
    alohaPlugins = "common/format"
    $("<script>", {src: alohaScriptUrl, "data-aloha-plugins": alohaPlugins})
      .bind("load ready", onAlohaLoad)
      .appendTo("head")

【问题讨论】:

    标签: javascript jquery coffeescript


    【解决方案1】:

    您可以通过 AJAX 将其作为文本获取,然后在脚本标签的 innerHTML 属性中提取。然后在附加它之前(或之后),您可以在该脚本元素上设置您的属性。

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "test.js", true);
    xhr.send(null);
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4)
            return;
    
        var script = document.createElement("script");
        script.innerHTML = xhr.responseText;
        script.setAttribute(); //add attributes
        document.body.appendChild(script);
    
        console.log("callback!");
    };
    

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多