项目作者: jonathanong

项目描述 :
React Asset Loader
高级语言: JavaScript
项目地址: git://github.com/jonathanong/react-asset-loader.git
创建时间: 2017-03-10T07:24:05Z
项目社区:https://github.com/jonathanong/react-asset-loader

开源协议:MIT License

下载


@jongleberry/react-asset-loader

@jongleberry/react-asset-loader"">NPM version
Build status
Test coverage
Dependency Status
License
@jongleberry/react-asset-loader"">Downloads

A wrapper component that loads assets for you.
Useful when you need to load external scripts only on certain components.

  • Define asset URLs by name.
  • Loads assets only once per URL globally.
  • Option to add callbacks to asset loads.
  • Supports CSS.
  • Simplified control flow using promises.

Example

Define your asset:

  1. import { set } from '@jongleberry/react-asset-loader'
  2. set('stripe', {
  3. url: 'https://js.stripe.com/v2/',
  4. // loads this asset in a global <script>
  5. type: 'js',
  6. // this logic will happen before the promise resolves
  7. resolve: x => x.then(() => Stripe.setPublishableKey('pk_test_somestuff'))
  8. })

Return a wrapped component:

  1. import AssetLoader from '@jongleberry/react-asset-loader'
  2. import SomeComponent from '../SomeComponent'
  3. export default AssetLoader(Component, [
  4. 'stripe'
  5. ])

Only show the original component if the Stripe SDK is loaded:

  1. import React, { Component, PropTypes } from 'react'
  2. export default class SomeComponent extends Component {
  3. static propTypes = {
  4. assetsFulfilled: PropTypes.bool.isRequired,
  5. }
  6. render () {
  7. if (!this.props.assetsFulfilled) return null
  8. return (
  9. <div>Hello world</div>
  10. )
  11. }
  12. }

API

set(name, options)

You need to define all your assets before using the asset loader.

Options are:

  • url - URL of the asset
  • resolve - a function to wrap the promise in. Signature: x => x.then(script => console.log(script))
  • type - type of asset, either js or css

const WrappedComponent = AssetLoader(Component, […assetNames])

Wrap a component to load assets by names.
The following properties will be injected into the Component‘s props:

  • assets<Object> - [name]: <Promise> hash look up
  • assetsFulfilled<Boolean> - whether all the assets were loaded
  • assetsRejected<Boolean> - whether one of the assets failed to load

get(name).then( => {})

Loads the asset, then returns the DOM element.
If you have a resolve() option, it will return the result of that instead.

You don’t really need to use this. Maybe if you want to “preload” assets.