Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

block-directory: simplify the LOAD_ASSETS flow by making it an async function #25956

Merged
merged 1 commit into from
Jan 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 20 additions & 31 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
* dependancy API.
* 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