'Getting currentScript is returning typeError
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.
Solution 1:[1]
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];
})();
}
Solution 2:[2]
I created another variable to hold the value from document and then it worked and no errors is shown.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
| Solution 2 | heliosk |
