The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

jugglinmike (4) [Avatar] Offline
#1
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?
benvinegar (68) [Avatar] Offline
#2
Re: Script Arguments with data- Attributes
Hi Mike,

No, there's no downsides (afaik). I was going to include it in this section, but thought it was slightly redundant because the code is 95% the same. But it deserves at least a passing mention.

- Ben
benvinegar (68) [Avatar] Offline
#3
Re: Script Arguments with data- Attributes
Hey Mike,

Just a heads up that the next update to the MEAP has this section.

- Ben