javascriptuncaught-reference-error

ReferenceError - External Script - Cannot access Variable


This is my custom code for a website:

<script>
function showCookieBanner () {
  //check lang_id
  var policy_id = 0;
  var lang_id = jQuery('html').attr('lang').split('-')[0];
  console.log(lang_id);
  if (lang_id === 'en') {
  policy_id = myID; 
  }
  else if (lang_id === 'de') {
  policy_id = myID; 
  }
  console.log(policy_id)

  //declare Variable for external script (_iub)
  var _iub = _iub || [];
  _iub.csConfiguration = {
  "lang": lang_id,
  "siteId": mySiteID,
  "cookiePolicyId": policy_id,
  };

  //run external script:
  var head= document.getElementsByTagName('head')[0];
  var script= document.createElement('script');
  script.src= '//cdn.iubenda.com/cs/iubenda_cs.js';
  script.type='text/javascript';
  script.charset='UTF-8';
  head.appendChild(script);
}
window.addEventListener('load', showCookieBanner);
</script>

With this script, I try to implement a cookie-banner solution from iubenda. First the lang_id of the HMTL document is checked. With the lang_id the policy_id is determined. And then passed to the variable _iub. The variable _iub is needed by the external script (see comment in the code). The whole thing has to happen when everything is loaded, so I use "window.addEventListener('load', showCookieBanner)".

Getting the lang_id and policy_id works (was checked with console.log), but I get the following error message, when I load the page:

iubenda_cs.js:1 Uncaught ReferenceError: _iub is not defined
    at iubenda_cs.js:1
    at iubenda_cs.js:1
(anonymous) @ iubenda_cs.js:1
(anonymous) @ iubenda_cs.js:1

Solution

  • Try to declare the '_iub' variable as global one, like this:

    var _iub = _iub || [];
    
    function showCookieBanner () {
       ...
    }