用javascript替换DOM并运行新脚本

时间:2013-06-29 13:32:59

标签: javascript html

我试图在页面加载时替换整个DOM,为用户创建的挖空页面执行no-js后备。

我将它替换为DOM,但是当我这样做时,新文档中包含的脚本没有运行。我想知道是否有任何方式强迫他们跑。

<!DOCTYPE html>
<html>
    <head>
        <title>Title1</title>
    </head>
    <body>
        Hello world <!-- No JS enabled content -->
    </body>
    <script type="text/javascript">
        var model = { 'template' : '\u003chtml\u003e\u003chead\u003e\u003ctitle\u003eTitle2\u003c/title\u003e\u003cscript type=\"text/javascript\"\u003ealert(\"test\");\u003c/script\u003e\u003c/head\u003e\u003cbody\u003eHello world2\u003c/body\u003e\u003c/html\u003e' };
        document.documentElement.innerHTML = model.template;
    </script>
</html>

模板包含以下编码

<html>
    <head>
        <title>aaa</title>
        <script type='text/javascript'>alert('hello world');</script>
    </head>
    <body>
        Hello world <!-- JS enabled content -->
    </body>
</html>

如何让警报运行?

1 个答案:

答案 0 :(得分:4)

正如您所发现的那样,您分配给script的文本中innerHTML标记中的代码不会被执行。有趣的是,在我尝试的每个浏览器上,script元素都是创建并放置在DOM中。

这意味着可以很容易地编写一个函数来按顺序运行它们,而不使用eval及其对范围的奇怪影响:

function runScripts(element) {
  var scripts;

  // Get the scripts
  scripts = element.getElementsByTagName("script");

  // Run them in sequence (remember NodeLists are live)
  continueLoading();

  function continueLoading() {
    var script, newscript;

    // While we have a script to load...
    while (scripts.length) {
      // Get it and remove it from the DOM
      script = scripts[0];
      script.parentNode.removeChild(script);

      // Create a replacement for it
      newscript = document.createElement('script');

      // External?
      if (script.src) {
        // Yes, we'll have to wait until it's loaded before continuing
        newscript.onerror = continueLoadingOnError;
        newscript.onload = continueLoadingOnLoad;
        newscript.onreadystatechange = continueLoadingOnReady;
        newscript.src = script.src;
      }
      else {
        // No, we can do it right away
        newscript.text = script.text;
      }

      // Start the script
      document.documentElement.appendChild(newscript);

      // If it's external, wait for callback
      if (script.src) {
        return;
      }
    }

    // All scripts loaded
    newscript = undefined;

    // Callback on most browsers when a script is loaded
    function continueLoadingOnLoad() {
      // Defend against duplicate calls
      if (this === newscript) {
        continueLoading();
      }
    }

    // Callback on most browsers when a script fails to load
    function continueLoadingOnError() {
      // Defend against duplicate calls
      if (this === newscript) {
        continueLoading();
      }
    }

    // Callback on IE when a script's loading status changes
    function continueLoadingOnReady() {

      // Defend against duplicate calls and check whether the
      // script is complete (complete = loaded or error)
      if (this === newscript && this.readyState === "complete") {
        continueLoading();
      }
    }
  }
}

当然,脚本无法使用document.write

请注意我们必须如何创建 new script元素。只是将现有文件移动到文档中的其他位置不起作用,浏览器将其标记为已运行(即使它不是)。

以上内容适用于大多数人在文档正文中的某个元素上使用innerHTML,但它不适合您,因为您实际上是在document.documentElement上执行此操作。这意味着NodeList我们从这一行回来了:

// Get the scripts
scripts = element.getElementsByTagName("script");

...随着我们向document.documentElement添加更多脚本,我们将继续扩展。因此,在您的特定情况下,您必须先将其转换为数组:

var list, scripts, index;

// Get the scripts
list = element.getElementsByTagName("script");
scripts = [];
for (index = 0; index < list.length; ++index) {
    scripts[index] = list[index];
}
list = undefined;

...以及稍后在continueLoading中,您必须手动从数组中删除条目:

// Get it and remove it from the DOM
script = scripts[0];
script.parentNode.removeChild(script);
scripts.splice(0, 1); // <== The new line

这是大多数人(不是你)的完整示例,包括脚本执行函数声明(如果我们使用eval会搞砸):Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Run Scripts</title>
</head>
<body>
  <div id="target">Click me</div>
  <script>
    document.getElementById("target").onclick = function() {
      display("Updating div");
      this.innerHTML =
        "Updated with script" +
        "<div id='sub'>sub-div</div>" +
        "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js'></scr" + "ipt>" +
        "<script>" +
        "display('Script one run');" +
        "function foo(msg) {" +
        "    display(msg); " +
        "}" +
        "</scr" + "ipt>" +
        "<script>" +
        "display('Script two run');" +
        "foo('Function declared in script one successfully called from script two');" +
        "$('#sub').html('updated via jquery');" +
        "</scr" + "ipt>";
      runScripts(this);
    };
    function runScripts(element) {
      var scripts;

      // Get the scripts
      scripts = element.getElementsByTagName("script");

      // Run them in sequence (remember NodeLists are live)
      continueLoading();

      function continueLoading() {
        var script, newscript;

        // While we have a script to load...
        while (scripts.length) {
          // Get it and remove it from the DOM
          script = scripts[0];
          script.parentNode.removeChild(script);

          // Create a replacement for it
          newscript = document.createElement('script');

          // External?
          if (script.src) {
            // Yes, we'll have to wait until it's loaded before continuing
            display("Loading " + script.src + "...");
            newscript.onerror = continueLoadingOnError;
            newscript.onload = continueLoadingOnLoad;
            newscript.onreadystatechange = continueLoadingOnReady;
            newscript.src = script.src;
          }
          else {
            // No, we can do it right away
            display("Loading inline script...");
            newscript.text = script.text;
          }

          // Start the script
          document.documentElement.appendChild(newscript);

          // If it's external, wait for callback
          if (script.src) {
            return;
          }
        }

        // All scripts loaded
        newscript = undefined;

        // Callback on most browsers when a script is loaded
        function continueLoadingOnLoad() {
          // Defend against duplicate calls
          if (this === newscript) {
            display("Load complete, next script");
            continueLoading();
          }
        }

        // Callback on most browsers when a script fails to load
        function continueLoadingOnError() {
          // Defend against duplicate calls
          if (this === newscript) {
            display("Load error, next script");
            continueLoading();
          }
        }

        // Callback on IE when a script's loading status changes
        function continueLoadingOnReady() {

          // Defend against duplicate calls and check whether the
          // script is complete (complete = loaded or error)
          if (this === newscript && this.readyState === "complete") {
            display("Load ready state is complete, next script");
            continueLoading();
          }
        }
      }
    }
    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  </script>
</body>
</html>

这里是your fiddle updated to use the above,我们将NodeList转换为数组:

HTML:

<body>
    Hello world22
</body>

脚本:

var model = {
    'template': '\t\u003chtml\u003e\r\n\t\t\u003chead\u003e\r\n\t\t\t\u003ctitle\u003eaaa\u003c/title\u003e\r\n\t\t\t\u003cscript src=\"http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js\"\u003e\u003c/script\u003e\r\n\t\t\t\u003cscript type=\u0027text/javascript\u0027\u003ealert($(\u0027body\u0027).html());\u003c/script\u003e\r\n\t\t\u003c/head\u003e\r\n\t\t\u003cbody\u003e\r\n\t\t\tHello world\r\n\t\t\u003c/body\u003e\r\n\t\u003c/html\u003e'
};
document.documentElement.innerHTML = model.template;

function runScripts(element) {
    var list, scripts, index;

    // Get the scripts
    list = element.getElementsByTagName("script");
    scripts = [];
    for (index = 0; index < list.length; ++index) {
        scripts[index] = list[index];
    }
    list = undefined;

    // Run them in sequence
    continueLoading();

    function continueLoading() {
        var script, newscript;

        // While we have a script to load...
        while (scripts.length) {
            // Get it and remove it from the DOM
            script = scripts[0];
            script.parentNode.removeChild(script);
            scripts.splice(0, 1);

            // Create a replacement for it
            newscript = document.createElement('script');

            // External?
            if (script.src) {
                // Yes, we'll have to wait until it's loaded before continuing
                newscript.onerror = continueLoadingOnError;
                newscript.onload = continueLoadingOnLoad;
                newscript.onreadystatechange = continueLoadingOnReady;
                newscript.src = script.src;
            } else {
                // No, we can do it right away
                newscript.text = script.text;
            }

            // Start the script
            document.documentElement.appendChild(newscript);

            // If it's external, wait
            if (script.src) {
                return;
            }
        }

        // All scripts loaded
        newscript = undefined;

        // Callback on most browsers when a script is loaded

        function continueLoadingOnLoad() {
            // Defend against duplicate calls
            if (this === newscript) {
                continueLoading();
            }
        }

        // Callback on most browsers when a script fails to load

        function continueLoadingOnError() {
            // Defend against duplicate calls
            if (this === newscript) {
                continueLoading();
            }
        }

        // Callback on IE when a script's loading status changes

        function continueLoadingOnReady() {

            // Defend against duplicate calls and check whether the
            // script is complete (complete = loaded or error)
            if (this === newscript && this.readyState === "complete") {
                continueLoading();
            }
        }
    }
}
runScripts(document.documentElement);

今天在阅读你的问题时我想到了这种方法。我以前从未见过它,但它适用于IE6,IE8,Chrome 26,Firefox 20和Opera 12.15。