Skip to content

Dynamic Frontend File Loader

Fred Chien edited this page Nov 2, 2015 · 3 revisions

There are some script and css files required we want to load dynamically when specific react component is being initialized. Lantern provided a decorator @loader to do this work for developer.

Import Loader Extension and Attach to Class

import { loader } from 'Decorator';

@loader
class MyComponent extends React.Component {
    // ignore ...
}

Load a Remote JavaScript File

this.loader.script('http://cdn.jsdelivr.net/jquery/2.1.4/jquery.min.js', function() {
    // Do something after loaded
});

Note that this.loader.script() won't call the callback function on server rendering.

Load multiple JavaScript Files

this.loader.script([
    'http://cdn.jsdelivr.net/jquery/2.1.4/jquery.min.js',
    'cdn.jsdelivr.net/semantic-ui/2.0.7/semantic.min.js'
], function() {
    // Do something after loaded
});

Load Remote CSS Files

this.loader.css('http://cdn.jsdelivr.net/semantic-ui/2.0.7/semantic.min.css', function() {
    // Do something after loaded
});