Another method of passing arguments to the script is using "data-" attributes. In terms of the example in 2.5, it would look like this:
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'http://camerastork.com/widget.js?product=1234';
script.setAttribute('data-product', '1234');
Although this approach yields behavior identical to using a fragment identifier, it also precludes the need for the regular expressions in the included script:
function getScriptElement() {
var scripts = document.getElementsByTagName('script'),
element,
src;
for (var i = 0; i < scripts.length; i++) {
element = scripts[ i ];
src = element.getAttribute ?
element.getAttribute('src') : el.src;
if (src && /ratingbuddy.com/widget.js/.test(src)) {
return element;
}
return null;
}
}
var script = getScriptElement();
var productId = script.getAttribute('data-product');
This approach seems preferable to using a fragment identifying because
- It seems to be faster
--- Both in the single case:
http://jsperf.com/passing-data-to-a-script
--- And scaling:
http://jsperf.com/passing-more-data-to-a-script
- It "jives" better semantically
- It doesn't require data be URI encoded
Do you know of any drawbacks to this approach?