Can ES6's module loader also load assets (html/css/…)

前端 未结 2 1241
时光说笑
时光说笑 2020-12-24 01:09

ES6\'s modules are based on a flexible loader architecture (although the standard is not final, so ...).

Does this mean ES6\'s loader, based on system.js, can load <

2条回答
  •  悲哀的现实
    2020-12-24 02:04

    I know you mentioned ES6 modules, but as that does not appear to support CSS natively, if you're looking for something standards-based to load resources dynamically and wish for something possibly somewhat less unpleasant than XMLHttpRequest, the new Fetch API might be used like this:

    var myStylesheets = ['myStyles1.css', 'myStyles2.css'];
    
    Promise.all(myStylesheets.map(url => fetch(url))).
        then(arr => Promise.all(arr.map(url => url.text()))).
        then(arr => {
            var style = document.createElement('style');
            style.textContent = arr.reduce(
                (prev, fileContents) => prev + fileContents, ''
            );
            document.head.appendChild(style);
        }).then(() => {
            // Do whatever now
        });
    

    This is even cleaner with async functions:

    var myStylesheets = ['myStyles1.css', 'myStyles2.css'];
    
    async function loadStyles(stylesheets) {
        let arr = await Promise.all(stylesheets.map(url => fetch(url)))
        arr = await Promise.all(arr.map(url => url.text()))
        const style = document.createElement('style')
        style.textContent = arr.reduce(
            (prev, fileContents) => prev + fileContents, ''
        )
        document.head.appendChild(style);
        // Do whatever now
    }
    
    loadStyles(myStylesheets)
    

    For other resource types, you can use the blob() method for images, and pending ES6 modules support, eval() for JavaScript, etc.

提交回复
热议问题