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

こ雲淡風輕ζ 提交于 2019-11-29 22:12:33
urish

If you use SystemJS then you can load assets by using plugins:

// Will generate a <link> element for my/file.css
System.import('my/file.css!')
    .then(() => console.log('CSS file loaded'));

Alternatively, you can use an import statement. This will make sure that the CSS file is loaded before the your script executes:

import 'my/file.css!';

Finally, you can retrieve the contents of the file using the text plugin:

import cssContent from 'my/file.css!text';
console.log('CSS file contents: ', cssContent);

Another option is to add the css as a dependency in JSPM config files. Basically adding the dependency in the specific package .json file and then running 'jspm install' which will add the override to package.js & jspm.config.js

Brett Zamir

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!