Skip to content

Commit

Permalink
MWPW-160156 - Add option to define mode (async, defer) when loading s…
Browse files Browse the repository at this point in the history
…cript (#3055)

* Update utils.js

* Add unit test

* Update utils.js

* incorporate review comments

* fix lint issue

* incorporate review comment
  • Loading branch information
Ruchika4 authored Oct 23, 2024
1 parent c30fa5b commit 7f9110e
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
3 changes: 2 additions & 1 deletion libs/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ export function appendHtmlToLink(link) {
}
}

export const loadScript = (url, type) => new Promise((resolve, reject) => {
export const loadScript = (url, type, { mode } = {}) => new Promise((resolve, reject) => {
let script = document.querySelector(`head > script[src="${url}"]`);
if (!script) {
const { head } = document;
Expand All @@ -405,6 +405,7 @@ export const loadScript = (url, type) => new Promise((resolve, reject) => {
if (type) {
script.setAttribute('type', type);
}
if (['async', 'defer'].includes(mode)) script.setAttribute(mode, true);
head.append(script);
}

Expand Down
3 changes: 2 additions & 1 deletion test/utils/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,10 @@ describe('Utils', () => {
});

it('Loads a script', async () => {
const script = await utils.loadScript('/test/utils/mocks/script.js', 'module');
const script = await utils.loadScript('/test/utils/mocks/script.js', 'module', { mode: 'async' });
expect(script).to.exist;
expect(script.type).to.equal('module');
expect(script.async).to.equal(true);
await utils.loadScript('/test/utils/mocks/script.js', 'module');
expect(script).to.exist;
});
Expand Down

0 comments on commit 7f9110e

Please sign in to comment.