Cutom HTML Tag - load javascript with custom attributes


I need to generate a custom html tag that runs a specific javascript, and passes custom attributes to it. Something like:
<script src="" data-cbid="some-numbers" data-blockingmode="auto" type="text/javascript"></script>
I use as trigger DOM ready, and this tag needs to be at head start as first, so top priority.

Problem is, the Tag gets fired but no attributes is passed. In my DOM i just get:
<script src="" type="text/javascript"></script>
and obviously the javascript fails.

Any tipps why the custom attributes are discarded?

Thanks for the help!


You could use a method very similar to the Matomo tracking code: Write a bit of JS that adds the script tag you want to the DOM.

The Matomo tracking code looks like this:

var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0];
g.type = 'text/javascript';
g.async = true;
g.defer = true;
g.src = u + 'statistics.js';
s.parentNode.insertBefore(g, s);

So you can fit this to your use case like this

const scriptEl = document.createElement('script')
const firstScript = document.getElementsByTagName('script')[0];
scriptEl.type = 'text/javascript';
scriptEl.src = ''
scriptEl.dataset.cbid = "some-numbers"
scriptEl.dataset.blockingmode = "auto"
firstScript.parentNode.insertBefore(scriptEl, firstScript);

or if you need to support older browsers (, and are okay with more ugly code

var scriptEl = document.createElement('script')
var firstScript = document.getElementsByTagName('script')[0];
scriptEl.type = 'text/javascript';
scriptEl.src = ''
scriptEl.setAttribute("data-cbit", "some-numbers")
scriptEl.setAttribute("blockingmode", "auto")
firstScript.parentNode.insertBefore(scriptEl, firstScript);

Hi Lukas, thanks a lot for your help!! it works! :partying_face: :partying_face:

1 Like