Skip to content

Commit 696489e

Browse files
Merge pull request #10 from julesterrien/feature-custom-attr
Set custom attributes + add test.
2 parents 35f41ca + 30460df commit 696489e

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ Called when the requested script is fully loaded.
2424
### `url` (required)
2525
URL pointing to the script you want to load.
2626

27+
### `attributes`
28+
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" />`
29+
2730
## Example
2831
You can use the following code to load jQuery in your app:
2932

src/index.jsx

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,14 @@ export default class Script extends React.Component {
88
onError: RPT.func.isRequired,
99
onLoad: RPT.func.isRequired,
1010
url: RPT.string.isRequired,
11+
attributes: RPT.object,
1112
};
1213

1314
static defaultProps = {
1415
onCreate: () => {},
1516
onError: () => {},
1617
onLoad: () => {},
18+
attributes: {},
1719
}
1820

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

7880
createScript() {
79-
const { onCreate, url } = this.props;
81+
const { onCreate, url, attributes } = this.props;
8082
const script = document.createElement('script');
8183

8284
onCreate();
8385

86+
// add 'data-' or non standard attributes to the script tag
87+
if (attributes) {
88+
Object.keys(attributes).forEach(prop => script.setAttribute(prop, attributes[prop]));
89+
}
90+
8491
script.src = url;
8592
script.async = 1;
8693

src/index.test.jsx

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
/* global document */
2+
13
import React from 'react';
24
import { shallow } from 'enzyme';
35
import Script from './index';
@@ -11,6 +13,11 @@ beforeEach(() => {
1113
onError: jest.fn(),
1214
onLoad: jest.fn(),
1315
url: 'dummy',
16+
attributes: {
17+
id: 'dummyId',
18+
dummy: 'non standard',
19+
'data-dummy': 'standard',
20+
},
1421
};
1522
wrapper = shallow(<Script {...props} />);
1623
});
@@ -75,3 +82,10 @@ test('componentWillUnmount should delete observers for the loader', () => {
7582
wrapper.instance().componentWillUnmount();
7683
expect(getObserver()).toBe(undefined);
7784
});
85+
86+
test('custom attributes should be set on the script tag', () => {
87+
const script = document.getElementById('dummyId');
88+
expect(script.getAttribute('id')).toBe('dummyId');
89+
expect(script.getAttribute('dummy')).toBe('non standard');
90+
expect(script.getAttribute('data-dummy')).toBe('standard');
91+
});

0 commit comments

Comments
 (0)