Skip to content

Commit

Permalink
Handle empty src attributes (#1254)
Browse files Browse the repository at this point in the history
Fixes #1253
  • Loading branch information
sebastianbenz authored Jul 12, 2021
1 parent fcabd18 commit 4790509
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
6 changes: 5 additions & 1 deletion packages/optimizer/lib/HtmlDomHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ function findMetaViewport(head) {
*/
function findRuntimeScript(head) {
for (let node = head.firstChild; node !== null; node = node.nextSibling) {
if (node.tagName === 'script' && node.attribs.src.match(/^https:\/\/.+\/v0(\.js|\.mjs)$/)) {
if (
node.tagName === 'script' &&
node.attribs.src &&
node.attribs.src.match(/^https:\/\/.+\/v0(\.js|\.mjs)$/)
) {
return node;
}
}
Expand Down
36 changes: 35 additions & 1 deletion packages/optimizer/spec/lib/HtmlDomHelper.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

const {findMetaViewport} = require('../../lib/HtmlDomHelper');
const {findMetaViewport, findRuntimeScript} = require('../../lib/HtmlDomHelper');
const treeParser = require('../../lib/TreeParser');
const {firstChildByTag} = require('../../lib/NodeUtils');

Expand Down Expand Up @@ -54,3 +54,37 @@ test('findMetaViewport returns the correct tag', async () => {
const result = findMetaViewport(head);
expect(result).toEqual(head.children[3]);
});

test('findRuntimeScript returns runtime v0.mjs', async () => {
const root = await treeParser.parse(`<html><head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.mjs"></script>
</head></html>`);
const html = firstChildByTag(root, 'html');
const head = firstChildByTag(html, 'head');
const result = findRuntimeScript(head);
expect(result).toEqual(head.children[3]);
});

test('findRuntimeScript returns runtime v0.js', async () => {
const root = await treeParser.parse(`<html><head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head></html>`);
const html = firstChildByTag(root, 'html');
const head = firstChildByTag(html, 'head');
const result = findRuntimeScript(head);
expect(result).toEqual(head.children[3]);
});

test('findRuntimeScript ignores empty src', async () => {
const root = await treeParser.parse(`<html><head>
<meta charset="utf-8">
<script id="amp-access" type="application/json"></script>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head></html>`);
const html = firstChildByTag(root, 'html');
const head = firstChildByTag(html, 'head');
const result = findRuntimeScript(head);
expect(result).toEqual(head.children[5]);
});

0 comments on commit 4790509

Please sign in to comment.