How do you append a script to the DOM body using jsdom and jQuery? The obvious answer of using $('body').append('<script src="..."></script>')
actually ends up adding the script in the document head
.
This is the basic node.js script I'm testing with:
var jsdom = require('jsdom');
jsdom.env(
"http://google.com",
['http://code.jquery.com/jquery-1.6.min.js'],
function(err, window) {
var $ = window.jQuery;
$('body').append('<script src="http://example.com/script.js"></script>');
console.log($('html').html());
}
);
which results in something beginning with:
<head><script src="http://example.com/script.js?_=1352426933034"></script>...
Interestingly, if you add a space in <sc ript src="..."></script>
this is appended correctly, so something (jsdom, I expect) is hijacking this script so it can add the cachebuster(?) and place it in the header. What's causing this and how do I prevent it from happening so it appends the script instead?
For what its worth,
$ npm ls
/Users/codyaray/dev/proxy/test
└─┬ jsdom@0.2.19
├─┬ contextify@0.1.3
│ └── bindings@1.0.0
├── cssom@0.2.5
├── cssstyle@0.2.3
├── htmlparser@1.7.6
└─┬ request@2.11.4
├─┬ form-data@0.0.3
│ ├── async@0.1.9
│ └─┬ combined-stream@0.0.3
│ └── delayed-stream@0.0.5
└── mime@1.2.7
I just encountered this issue with jsdom, only I want to append the <script>
to <head>
.
Following code:
$('head').append('<script type="text/javascript" src="script.js"></script>');
resulted in this:
<head>
<script type="text/javascript" src="script.js"></script>
<script src="script.js?_=1352426933034"></script>
</head>
This seems to be only happening when appending <script>
element with src
attribute already set. All seems to be all right when you first append empty <script>
and then set its src
like this:
$('<script>').appendTo($('head')).attr('src','script.js');