我看起来就像当我浏览一页时jsdom
, the $(document).ready
页面脚本中的块没有被执行。
这是 HTML:
<html>
<body>
If everything works, you should see a message here: <h2 id="msg"></h2>
<script>
var checkpoint1 = true
var checkpoint2 = false
$(document).ready(function(){
checkpoint2 = true
$('#msg').html("It works, it works, it works!")
})
</script>
</body>
</html>
和法典:
fs = require('fs');
htmlSource = fs.readFileSync("public/examples/test_js_dom.html", "utf8");
global.jsdom = require("jsdom");
jsdom.defaultDocumentFeatures = {
FetchExternalResources : ['script'],
ProcessExternalResources : ['script'],
MutationEvents : '2.0',
QuerySelector : false
};
doc = jsdom.jsdom(htmlSource)
window = doc.createWindow()
jsdom.jQueryify(window, "http://code.jquery.com/jquery-1.8.3.min.js", function(){
console.log(window.checkpoint1);
console.log(window.checkpoint2);
console.log(window.$().jquery)
console.log("body:");
console.log(window.$('body').html());
});
和输出:
Bee@cleanroom:~/projects/notjs$ test/jsdom.js
true
false
1.8.3
body:
If everything works, you should see a message here: <h2 id="msg"></h2>
<script>
var checkpoint1 = true
var checkpoint2 = false
$(document).ready(function(){
checkpoint2 = true
$('#msg').html("It works, it works, it works!")
})
</script>
<script class="jsdom" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
我究竟做错了什么?
添加细节以满足荒谬的 stackoverflow 比率。
Bee@cleanroom:~/projects/notjs$ npm ls jsdom
[email protected] /cdn-cgi/l/email-protection /Users/Bee/projects/notjs
├─┬ [email protected] /cdn-cgi/l/email-protection
│ └── [email protected] /cdn-cgi/l/email-protection
└── [email protected] /cdn-cgi/l/email-protection
Bee@cleanroom:~/projects/notjs$ node -v
v0.8.15
Bee@cleanroom:~/projects/notjs$ npm -v
1.1.66
[解决方案]:
谢谢戴夫引导我找到正确的答案。
我认为完整的 jsdom 答案是这样的;不要使用 jsdom.jQuerify,添加脚本标记以在页面脚本上方的页面中加载 jQuery(因为需要这样做才能在浏览器中加载页面)。
html:
...
If everything works, you should see a message here: <h2 id="msg"></h2>
<script src="http://notjs.org/vendor/jquery-1.8.3.min.js"></script>
<script>
var checkpoint1 = true
var checkpoint2 = false
$(document).ready(function(){
var checkpoint2 = true
...
code:
...
doc = jsdom.jsdom(htmlSource)
window = doc.createWindow()
window.addEventListener('load', function(){
console.log(window.checkpoint1);
console.log(window.checkpoint2);
console.log(window.$().jquery)
console.log("body:");
console.log(window.$('body').html());
});
...