Skip to content

Commit b2ebe12

Browse files
committed
Insert script at the end if HTML has no body tag
1 parent a27d0a2 commit b2ebe12

File tree

4 files changed

+29
-3
lines changed

4 files changed

+29
-3
lines changed

lib/script-injector.js

+19-3
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,30 @@ function scriptInjector (script) {
3434
function () {
3535
if (needToAddScript) {
3636
this.push(script);
37+
needToAddScript = false;
3738
}
3839
this.push(null);
3940
}))
4041
.pipe(bodyTag);
4142

42-
tr1.pipe(tr2);
43-
44-
return duplexer(tr1, tr2);
43+
// If there were no <body>'s even, append the script at the end of the file
44+
var tr3 = through(
45+
function (data, enc, cb) {
46+
this.push(data);
47+
cb();
48+
},
49+
function () {
50+
if (needToAddScript) {
51+
this.push(script);
52+
needToAddScript = false;
53+
}
54+
this.push(null);
55+
}
56+
);
57+
58+
tr1.pipe(tr2).pipe(tr3);
59+
60+
return duplexer(tr1, tr3);
4561
}
4662

4763
module.exports = scriptInjector;

test/dat/test4-output.html

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<h1>Hello World</h1>
2+
<p>This file is a result of X-to-HTML conversion, or not.</p>
3+
<script type="text/javascript">
4+
;(function someCode() {
5+
console.log("I'm some code to be inserted inline");
6+
})()
7+
</script>

test/dat/test4.html

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<h1>Hello World</h1>
2+
<p>This file is a result of X-to-HTML conversion, or not.</p>

test/test.js

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ var testRunner = function (filename, t) {
1919
test('inject code before the closing body tag', testRunner.bind(null, 'test1'));
2020
test('inject code before the first script tag in the header', testRunner.bind(null, 'test2'));
2121
test('inject code before the first script tag in the body', testRunner.bind(null, 'test3'));
22+
test('inject code when there is no body tag', testRunner.bind(null, 'test4'));
2223

2324
function someCode () {
2425
console.log("I'm some code to be inserted inline");

0 commit comments

Comments
 (0)