Skip to content

Commit

Permalink
block-directory: simplify the loadAssets flow by making it an async f…
Browse files Browse the repository at this point in the history
…unction (#25956)
  • Loading branch information
jsnajdr authored Jan 7, 2021
1 parent 4171f3f commit b119559
Showing 1 changed file with 19 additions and 30 deletions.
49 changes: 19 additions & 30 deletions packages/block-directory/src/store/controls.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,47 +62,36 @@ export function loadAssets( assets ) {
}

const controls = {
LOAD_ASSETS() {
async LOAD_ASSETS() {
/*
* Fetch the current URL (post-new.php, or post.php?post=1&action=edit) and compare the
* JavaScript and CSS assets loaded between the pages. This imports the required assets
* for the block into the current page while not requiring that we know them up-front.
* In the future this can be improved by reliance upon block.json and/or a script-loader
* dependency API.
*/
return apiFetch( {
const response = await apiFetch( {
url: document.location.href,
parse: false,
} )
.then( ( response ) => response.text() )
.then( ( data ) => {
const doc = new window.DOMParser().parseFromString(
data,
'text/html'
);
} );

const data = await response.text();

const doc = new window.DOMParser().parseFromString( data, 'text/html' );

const newAssets = Array.from(
doc.querySelectorAll( 'link[rel="stylesheet"],script' )
).filter(
( asset ) =>
asset.id && ! document.getElementById( asset.id )
);
const newAssets = Array.from(
doc.querySelectorAll( 'link[rel="stylesheet"],script' )
).filter(
( asset ) => asset.id && ! document.getElementById( asset.id )
);

return new Promise( async ( resolve, reject ) => {
for ( const i in newAssets ) {
try {
/*
* Load each asset in order, as they may depend upon an earlier loaded script.
* Stylesheets and Inline Scripts will resolve immediately upon insertion.
*/
await loadAsset( newAssets[ i ] );
} catch ( e ) {
reject( e );
}
}
resolve();
} );
} );
/*
* Load each asset in order, as they may depend upon an earlier loaded script.
* Stylesheets and Inline Scripts will resolve immediately upon insertion.
*/
for ( const newAsset of newAssets ) {
await loadAsset( newAsset );
}
},
};

Expand Down

0 comments on commit b119559

Please sign in to comment.