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
Try to declare the '_iub' variable as global one, like this:
var _iub = _iub || [];
function showCookieBanner () {
...
}
Related
I am trying to inject a script on page load in head wherein I have to give the page name inside script.
Below is how I am implementing it in my ts file.
**var head = document.getElementsByTagName('head')[0];
var tag = document.createElement("script");
tag.type = 'text/javascript';
tag.innerHTML = "var DDO = {} DDO.pageData = {'pageName': " + pageUrl + "} ";
head.appendChild(tag);**
The script is getting injected however an error is being thrown in the console tab.
ERROR: VM3741:1 Uncaught SyntaxError: Unexpected identifier at appendChild
Try this
var head = document.getElementsByTagName('head')[0],pageUrl="somevalue";
var tag = document.createElement("script");
tag.type = 'text/javascript';
tag.textContent = "var DDO = {}; DDO.pageData = {'pageName': '" + pageUrl + "'} ";
head.appendChild(tag);
To remove previous script element
var script = head.childNodes[0]; //get previous script element
head.removeChild(script); //removing script
you have not provided single quotes for the value of the key pageName
tag.innerHTML = "var DDO = {}; DDO.pageData = {'pageName': " + pageUrl + "} ";
semicolon missing after defining the variable DDO,
and also from where are you injecting in pageUrl, make sure variable is defined.
try having script in external file and injecting in script tag with refrence to that file in case some error in script defined in inner html
document.head, document.body to attach scripts
Correct Answer:
var head = document.getElementsByTagName('head')[0];
var tag = document.createElement('script');
tag.type = 'text/javascript';
tag.id = 'adobedatalayer';
tag.textContent = 'var DDO = {}; DDO.pageData =' + JSON.stringify(pageinfo);
var script = document.getElementById('adobedatalayer');
if (script != null) {
head.removeChild(script);
}
head.appendChild(tag);
I created a script that add javascript files by appending it to the head tag.
Using the code below that I created:
var Dim = (function(s){
var storage;
function loadError (oError) {
throw new URIError("The script " + oError.target.src + " is not accessible.");
}
return {
require : function(script,callback){
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.onerror = loadError;
if (callback) {
oScript.onload = callback;
}
document.head.appendChild(oScript);
oScript.src = script;
}
};
})();
When we use the script like this:
Dim.require("script.js", function(){alert(token)}); alert(token);
and script.js code is:
alert(" Ok"); var token = " Hello";
The alert(token) throws an error.
Can anyone point me the Problem?
[Question was edited]
Dim.require("script.js", function(){alert(token)}); alert(token);
It runs first alert because its in callback which is called when the script is loaded by the browser.
if (callback) {
oScript.onload = callback;
}
And second is not giving you an alert because it gives you an error
Uncaught ReferenceError: token is not defined
You are loading your script.js asynchronously and while executing second alert , the script.js not loaded yet.
I have my UI's split up in 2 javascript files. If the URL is of certain patter lets say /test1 then I want script1 to execute or in other words, I want script1 to be added as <include> so the UI renders according to script1 else I want script2 to be added for /test2.
There is no button that triggers these URLs. Its when the page loads -detect URL and load script accordingly.
How can I achieve this?
you can dynamically insert javascript file.
<script type="application/javascript">
function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
if(type === "test1")
loadJS('file1.js')
else
loadJS('file2.js');
</script>
using jquery and javascript:
$(document).ready(function(){
var url=location.href//get the page url
var scriptUrl
if(url.indexOf('something')>0){//check for specific string in url
scriptUrl='/script1.js'
}
else{
scriptUrl='/script2.js'
}
var script = document.createElement( 'script' );//create script element
script.type = 'text/javascript';
script.src = scriptUrl;
$("head").append( script );//append newly created script element to head
})
Query String Examples:
?page=test1
?page=test2
Following code will check the value of page and then load the appropriate Script:
$(document).ready(function () {
var page = $.getUrlVar("page");
var scriptToRun = null;
switch (page) {
case "test1":
scriptToRun = "script1.js";
break;
case "test2":
scriptToRun = "script2.js";
break;
}
// Create Script Tag
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptToRun;
$("head").append(script);
});
Be sure to add the following Extension before your $(document).ready code:
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
(This jQuery Extension is not my Code).
I am a JavaScript newbie and learn by working on a pure JavaScript "project" that calculates mathematical functions. It all works well. Now, as a further step, I want to make the messaging multilingual. The code should be capable of loading the appropriate language file at runtime. For the dynamic loading issue, I read and found solutions on Web pages like this one.
Before writing the dynamic code, I loaded it statically and the test code worked well. The code I am asking for help about is just making the minor difference of loading a "script" element.
The code where I run into problems is the this.getString function, where it is not possible to access the de element in the language file. At line console.log(eval(language, tag));, I get the error message "Uncaught ReferenceError: de is not defined".
//File: Utils/Lang/js/FileUtils.js
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
loadFile("js/resources/lang.de.js");
return;
} ()
this.getString = function(tag, strDefault) {
console.log("getString(" + tag + ", " + strDefault + "): ");
console.log("getString(...): document = " + document);
console.log("getString(...): eval(" + language + ", " + tag + ") = ");
console.log(eval(language, tag));
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined')
? strDefault
: eval('en.' + tag);
}
}
}
The static test code that works is not included, where I can access the de element.
My question: How to load the language file properly so that the de tag is accessible?
Thank you for your help!
//File: Utils/Files/js/FileUtils.js
function loadFile(filepathname) {
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
console.log("loadFile(\"" + filepathname + "\"): document = " + document);
}
//File: Utils/Lang/js/resources/lang.de.js:
de = {
pleaseWait: "Bitte warten..."
};
//File: Utils/Lang/js/resources/lang.en.js
en = {
pleaseWait: "Please wait..."
};
//File: Utils/Lang/js/TestLanguage.js:
function output() {
console.log("output()");
var codes = ['de', 'en'];
for (var i = 0; i < codes.length; i++) {
var translator = new Language(codes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
<!--File: Utils/Lang/TestLang.html:-->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="js/Language.js"></script>
<script type="text/javascript" src="js/TestLanguage.js"></script>
</head>
<body>
<button name="outputButton" onclick="output();">Click</button>
<br>Please press [F12] so that you can see the test results.
</body>
</html>
When you add the script tag to your document, it is not loaded synchronously. You need to wait for the file to be loaded before you can use the code that was in it.
you may be able to redesign your code to use a script.onload callback:
var reference = document.createElement('script');
// ...
reference.onload = function() {
alert("Script loaded and ready");
};
but for this scenario, if you don't have many language string you may be best to just load them all statically.
How to dynamically load a script file (the most basic version, also there are multiple options to this):
function loadScriptFile(scriptPath, jsFile, callBack)
{
var scriptTag = document.createElement("script"); //creates a HTML script element
scriptTag.language = "JavaScript"; //sets the language attribute
scriptTag.type = "text/javascript";
scriptTag.src = scriptPath + jsFile + ".js"; //the source
if (callBack)
{
scriptTag.onload = callback; //when loaded execute call back
}
var scriptTagParent = document.getElementsByTagName("script")[0];
if (scriptTagParent)
{
scriptTagParent.parentNode.insertBefore(scriptTag, scriptTagParent);
}
else
{
document.body.appendChild(scriptTag);
}
}
How it works:
Run loadScriptFile("scripts", "math", startProgram). The first two arguments will point to your file and folder. The last argument is a callback function. When defined this will be executed once the script tag has finished loading and the script is available in the global scope. The script will be dynamically added to your page. If there is a script element present on the page, this will be added before that (to keep the mark up nice). If not it will be appended to the body. (this is only visual).
The callback part is the most interesting. Since your script will now be asynchronical, you'll need to use callback to tell your program that the necessary files are loaded. This callback is fired when the script file is loaded, so you won't get script errors.
Just a basic example of what I meant in my comment:
This is not an answer to your question, it's an alternative way (I think it's better to manage). Pure Javascript (with help of XML)
XML-file: language.xml
Basic XML structure:
<language>
<l1033 name="english" tag="en-US">
<id1000>
<![CDATA[
Hello World!
]]>
</id1000>
</l1033>
<l1031 name="german" tag="de-DE">
<id1000>
<![CDATA[
Hallo Welt!
]]>
</id1000>
</l1031>
</language>
What did I do:
I constructed a root element called language. Within that wrote two language strings called l1033 for English and l1031 for German. Note that a letter is prepended before the language code. XML will throw an error when a tag starts with a digit. a CDATA block is used to prevent any problems with special characters.
Now the loading will be done by AJAX:
var xmlLoader = new XMLHttpRequest();
xmlLoader.onreadystatechange = trackRequest; //event to track the request, with call back
xmlLoader.open("get", "language.xml", true); //set asynchronous to true
xmlLoader.send(null);
function trackRequest()
{
if (this.status == 200 && this.readyState == 4) //all is good
{
globalLanguageFile = this.responseXML;
startProgram(); //fictive function that starts your program
}
}
Now the XML is loaded. How to load strings from it?
function loadLanguageString(code, id, fallback)
{
var word = fallback;
if (globalLanguageFile.getElementsByTagName("l"+code).length > 0)
{
if (globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id).length > 0)
{
//found the correct language tag and id tag. Now retrieve the content with textContent.
word = globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id)[0].textContent;
}
}
return word; //when failed return fall back string
}
How to call the function:
loadLanguageString(1031, 1000, "Hello World!");
I found the right answer to my question using the info from GarethOwen. Here are the code modifications I had to do:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Arrays/js/ArrayUtils.js"></script>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="../Logic/js/LogicalUtils.js"></script>
<script type="text/javascript" src="js/LanguageUtils.js"></script>
<script type="text/javascript" src="js/TestLanguageUtils.js"></script>
</head>
<!-- body onload="load(null, '../Maths/js/resources')" -->
<body onload="load();">
<button onclick="output();">Click</button><br>
Please press [F12] so that you can see the test results.
</body>
</html>
TestLanguage.html: Augmented the body tag
<body onload="load()">
TestLanguage.js:
2a. Added the load() function requested by the HTML page now:
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < codes.length; i++) {
new Language(codes[i]);
}
}
2b. Using the global gCodes variable also in the output() function
Language.js: To test the whole better, I made the code in the function Language a little bit more elaborate by changing the line in the constructor in function Language(language) to:
// Load the proper language file:
if (eval("gLoaded.indexOf('" + language + "') < 0")) {
loadFile("js/resources/lang." + language + ".js");
gLoaded[gLoaded.length] = language;
}
Thank you for your support! :-)
//Lang/js/Lang.js:
"use strict";
/**
* Object for multilingual message handling.
*
* #param language
*/
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
switch (language) {
case "de":
loadFile("js/resources/lang.de.js");
break;
case "tr":
loadFile("js/resources/lang.tr.js");
break;
default:
loadFile("js/resources/lang.en.js");
}
return;
}()
/**
* Returns the language of that object.
*
* #returns The language
*/
this.getLanguage = function() {
var strLanguage;
switch (language) {
case "de":
strLanguage = "German";
break;
case "tr":
strLanguage = "Turkish";
break;
default:
strLanguage = "English";
}
return strLanguage;
}
/**
* Returns the language code of that object.
*
* #returns The language code
*/
this.getString = function(tag, strDefault) {
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined') ? strDefault : eval('en.' + tag);
}
}
}
//Lang/js/TestLang.js:
"use strict";
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < gCodes.length; i++) {
new Language(gCodes[i]);
}
}
/**
* Object for multilingual message handling.
*
* #param language
*/
function output() {
console.log("output()");
for (var i = 0; i < gCodes.length; i++) {
var translator = new Language(gCodes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
//Utils/Files/js/FileUtils.js:
"use strict";
/**
* Object with file utilities
*
* #param filepathname
*/
function loadFile(filepathname) {
var methodName = "loadFile(" + filepathname + "): "
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
reference.onload = function() {
console.log(methodName + "onload(): Language script loaded and ready!");
}
}
Here is the console output:
Here is the output:
load()
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
output()
output(): in German: Bitte warten...
output(): in English: Please wait...
output(): in Turkish: Lütfen bekleyiniz...
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
my javascript function is throwing this error
var cycles = 0;
var exec_next = null;
function timer_interrupt() {
cycles++;
if (exec_next) {
var cmd = exec_next;
exec_next = null;
cmd();
}
}
using firebug it says the } should be at the end of the cycles++; what to do? I don't have any xml script being displayed?
it is being included in my template like this
<script language="JavaScript" src="mysript.js">
</script>