I'm trying to get a custom attribute that I put on my script tag:
<script type="text/javascript" src="https://.../mysource.js" customdata="some_value"></script>
I'm using the following code so it will work on IE:
document.currentScript =
document.currentScript ||
(function () {
const field = document.getElementsByTagName('script');
return field[field.length - 1];
})();
// document.currentScript.getAttribute('customdata');
But then I'm receving the following error when I try to set a new value on document.currentScript.
Uncaught TypeError: Cannot set property currentScript of # < Document > which has only a getter
I only solve this when I'm using document.currentScript directly, but then I can't use on older browsers.
I created another variable to hold the value from document and then it worked and no errors is shown.
If document.currentScript exists, it's a read-only property. So only try to set it if it doesn't exist.
if (!document.currentScript) {
document.currentScript = (function() {
const field = document.getElementsByTagName('script');
return field[field.length - 1];
})();
}