JSDOM脚本包括更多脚本问题

时间:2013-10-17 22:17:58

标签: javascript node.js jsdom

我正在使用 jsdom 来读取包含头部脚本的HTML文件,而脚本又包含更多脚本。我的问题是html加载中的脚本没有问题,但是它们包含的脚本没有被执行。

server.js

var fs = require('fs');
var jsdom = require('jsdom');
var doc = jsdom.jsdom(fs.readFileSync("./index.html"), null, {
    features: {
        FetchExternalResources   : ['script'],
        ProcessExternalResources : ['script'],
        MutationEvents           : '2.0',
    }
});

var window = doc.createWindow();
// Wait for the window to load so all the scripts are available.
window.addEventListener('load', function() {
    // Print all the script tags in the html
    var scripts = window.document.getElementsByTagName('script');
    scripts = Array.prototype.slice.call(scripts);
    scripts.forEach(function(val) {
        console.log(val.src);
    });

    // The loop above prints out
    // =============================
    // index.js
    // another.js

    // It should be
    // =============================
    // index.js   -> In the html
    // another.js -> Added by index.js
    // testing.js -> Added by another.js but should not load since there is no file. That is expected.

    console.log('test1: ' + window.test1); // This works! :)
    console.log('test2: ' + window.test2); // This fails :(
});

的index.html

<!DOCTYPE html>
<html>
    <head>
        <!-- This will add a script tag for another.js -->
        <script src="index.js"></script>
    </head>
    <body>

    </body>
</html>

index.js

var script = document.createElement('script');
script.src = "another.js";
document.getElementsByTagName('head')[0].appendChild(script);
window.test1 = 'hello world'; // This works

another.js

// For some reason this file is not being evaluated.
window.test2 = 'hello world';
var script = document.createElement('script');
script.src = "testing.js";
document.getElementsByTagName('head')[0].appendChild(script);

我会永远感激能帮助我的人。

0 个答案:

没有答案