Code Monkey home page Code Monkey logo

react-load-script's Introduction

react-load-script CircleCI Dependency Status

This package simplifies loading of 3rd party scripts in your React applications.

Motivation

There are situations when you need to use a 3rd party JS library in your React application (jQuery, D3.js for rendering charts, etc.) but you don't need it everywhere and/or you want to use it only in a response to users actions. In cases like this, preloading the whole library when application starts is an unnecessary and expensive operation which could possibly slow down your application.

Using the Script component this package provides you with, you can easily load any 3rd party scripts your applications needs directly in a relevant component and show a placeholder while the script is loading (e.g. a loading animation). As soon as the script is fully loaded, a callback function you'll have passed to Script is called (see example below).

Supported React versions

This package requires React 0.14.9 and higher.

API

The package exports a single component with the following props:

onCreate

Called as soon as the script tag is created.

onError (required)

Called in case of an error with the script.

onLoad (required)

Called when the requested script is fully loaded.

url (required)

URL pointing to the script you want to load.

attributes

An object used to define custom attributes to be set on the script element. For example, attributes={{ id: 'someId', 'data-custom: 'value' }} will result in <script id="someId" data-custom="value" />

Example

You can use the following code to load jQuery in your app:

import Script from 'react-load-script'

...

render() {
  return (
    <Script
      url="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
      onCreate={this.handleScriptCreate.bind(this)}
      onError={this.handleScriptError.bind(this)}
      onLoad={this.handleScriptLoad.bind(this)}
    />
  )
}

...

handleScriptCreate() {
  this.setState({ scriptLoaded: false })
}

handleScriptError() {
  this.setState({ scriptError: true })
}

handleScriptLoad() {
  this.setState({ scriptLoaded: true })
}

License

MIT 2016

Made with love by

react-load-script's People

Contributors

jakubkottnauer avatar julesterrien avatar modestjoust avatar ondrejbartas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-load-script's Issues

About prop-types

Hellos guys,

More than an issue, is a question, when I added the component I got this warning:

Warning: Failed propType: Calling PropTypes validators directly is not supported by the prop-types package

I read about this but I can't fix it.

Thanks!

Question on using Script to load api key

For example, can I do something like this:

<Script>
  url="http://api.map.baidu.com/api?v=2.0&ak=FUmG8hLpACVnEatoLyLNGSIG4SY6VAIM"
  onCreate={this.handleScriptCreate.bind(this)}
  onError={this.handleScriptError.bind(this)}
  onLoad={this.handleScriptLoad.bind(this)}
</Script>

Loading multiple, dependent scripts

Is it possible to load multiple, dependent scripts prior to executing any code in the handleScriptLoad() as shown in the example?

I tried using multiple <Script /> blocks in the desired dependency order, but that didn't seem to work out quite as expected.

Passing custom arguments to the script

Hey! What do you think of including the ability to pass custom props to the scripts that could be included either as attributes of the script tag, or as a data- attributes

For eg.

<Script
url="https://someUrl.com"
customProp="customPropValue"
onCreate={onCreate}
onError={onError}
onLoad={onLoad}
/>

At quick glance, the only edit necessary would be to change createScript to grab these props and add them to the script:

createScript() {
		const { onCreate, url, ...customProps } = this.props;
		const script = document.createElement('script');

		onCreate();

		if (customProps) {
                        // to include them as script attributes
			Object.keys(customProps).forEach((prop) => {
				script.setAttribute(prop, customProps[prop]);
			});
                       // or something like script.setAttribute(`data-${prop}`, customProps[prop]);
		}

		script.src = url;
		script.async = 1;

TypeScript types definition

Using React with TypeScript (TSX) requires type definitions for node modules. Are there plans to release TypeScript definition (*.d.ts) for this module?

react16 support

now that react16 has been published, would it be possible to update the dependencies to reflect this? Thanks!

How to reload the script.

Hi i am trying to load a script but sometimes it loads successfully but sometimes it does not.Is their a way i can manually reload the script in case of any error comes up and the script does not load so that the user does not face any issues while using the app...?

How to use 3rd script's function

I had add 3rd script in my react files, and I want to use 3rd script's function in my react component, but it will be error about undefind.

How to use?

I'm a little confused about the example: I have

handleScriptCreate() {
  this.setState({ scriptLoaded: false })
}
 
handleScriptError() {
  this.setState({ scriptError: true })
}
 
handleScriptLoad() {
  console.log(this)
  this.setState({ scriptLoaded: true })
  $('body').click(function(){
		alert('up')
   })
}
 
render() {
   return(

    <Script
      url="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
      onCreate={this.handleScriptCreate.bind(this)}
      onError={this.handleScriptError.bind(this)}
      onLoad={this.handleScriptLoad.bind(this)}
    />
  )
}

and I'm getting a error '$' is not defined . jQuery in component did mount doesn't work either. What am I doing wrong?

Can't change the component once it's mounted to the DOM

I have a use case where the src element of the script tag changes according to the locale used on the website. Since the script src is passed using the url prop, I thought the component would re-render when changing it, but it doesn't. After looking at your code I realized that that the component is never rendered using render(). Rather, you're using observers created in componentDidMount(). It means that once the component has been mounted to the DOM, it will never be re-rendered again.

I know that because of this design choice it probably won't be that easy to make it possible for the component render using the render() method so it gets re-rendered when props change without a possible (major) refactoring. Just wanted to let you guys know about it if you never encountered the problem. If you don't plan on implementing this, maybe adding a note to the documentation would help some people save time since I had to check your code to understand why my component was not rendering correctly.

#14 might be related to this - I haven't used react-router enough so far to fully understand the problem.

Re-rendering script

Hello,

I'm new to react and I'm using react-load-script for rendering a bokeh Chart served by my python (flask/pandas/bokeh) server.
I'm able to load a first script and display a chart given some arguments but when I change the arguments and try to re render nothing happens.

Do you know how to handle this problem ?

Allow async=false via prop attributes

Hey, it looks like async is set to true (1) in src/index:92 after custom attributes are set (src/index:88). Is it possible to be able to set async to false via custom attributes?

Thanks!

Local scripts?

How do I load locally stored scripts? I need to integrate coinbase with my project, but they require a local script to be loaded, with an id at the script tag, thus I'm using react-load-script, but it's not working for local scripts.

Edit: I'm using parcel-js as my packager.

Script not be removed when the Parent Component unmounted.

I use react-load-script in my SPA , and i only need the scripts be loaded when a Wrapper Component mounted, when i route to an another Wrapper Component , the old scripts should be removed and new scripts will loaded, but it did not work like this, the old scripts conflicts to the new scripts, so it works bad.

How to *not* load a script if it's already loaded...

Working on an React App, trying to get Paypal SDK to work.

The initial load works fine, but if the user navigates away from the page and back, things fail:

Error: Expected element to be passed to render iframe

How can you conditionally load the script, so that it's only loaded once based on the existence of window.paypal?

I've tried various conditionals in handleScriptCreate and handleScriptLoad, but I've not found the secret sauce.

Any advice would be appreciated.

How to detect if the script is already loaded?

Hi,
i use react-load-script to load a script in a component.
If this component is instantiated a second time, i wanna detect if the script was loaded before.

Does react-load-script support this functionality?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.