Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ 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:

Expand Down
9 changes: 8 additions & 1 deletion src/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ export default class Script extends React.Component {
onError: RPT.func.isRequired,
onLoad: RPT.func.isRequired,
url: RPT.string.isRequired,
attributes: RPT.object,
};

static defaultProps = {
onCreate: () => {},
onError: () => {},
onLoad: () => {},
attributes: {},
}

// A dictionary mapping script URLs to a dictionary mapping
Expand Down Expand Up @@ -76,11 +78,16 @@ export default class Script extends React.Component {
}

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

onCreate();

// add 'data-' or non standard attributes to the script tag
if (attributes) {
Object.keys(attributes).forEach(prop => script.setAttribute(prop, attributes[prop]));
}

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

Expand Down
14 changes: 14 additions & 0 deletions src/index.test.jsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* global document */

import React from 'react';
import { shallow } from 'enzyme';
import Script from './index';
Expand All @@ -11,6 +13,11 @@ beforeEach(() => {
onError: jest.fn(),
onLoad: jest.fn(),
url: 'dummy',
attributes: {
id: 'dummyId',
dummy: 'non standard',
'data-dummy': 'standard',
},
};
wrapper = shallow(<Script {...props} />);
});
Expand Down Expand Up @@ -75,3 +82,10 @@ test('componentWillUnmount should delete observers for the loader', () => {
wrapper.instance().componentWillUnmount();
expect(getObserver()).toBe(undefined);
});

test('custom attributes should be set on the script tag', () => {
const script = document.getElementById('dummyId');
expect(script.getAttribute('id')).toBe('dummyId');
expect(script.getAttribute('dummy')).toBe('non standard');
expect(script.getAttribute('data-dummy')).toBe('standard');
});