Load Javascript on function call - javascript

I am trying to load one of my advertisers javascript on a click event but I am getting errors from the javascript when it loads.
var get_ad_popup = function () {
_adUnit= {settings: {siteID: 'T1446', pop: {type: 'popunder'}} };
(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
s.src = "http://cdn.adunit.com/js/gp.min.js";
var e = document.getElementsByTagName('script')[0];
e.parentNode.insertBefore(s, e);
})();
};
Then when I call the function I get this error in the console.
TypeError: _adUnit.pop.clkPop is not a function
If I look in the head I can see that the javascript was properly loaded. I just wondering why I get this error.
Edited:
If I load the javascript outside of the function and just include it in the head then it works just fine.
The script can be seen here: http://jsfiddle.net/QXTkz/
This is provided to me by my advertiser.

Related

IBM forms experience External library error :jsPDF

so I was following the current standard way of adding an external js library to forms experience builder (tutorial: https://www.youtube.com/watch?v=wRW4vBUT4oM).
I was able to successfully add jquery and run jquery codes, but i am not able to run the jsPDF library, I am getting a reference error "ReferenceError: jsPDF is not defined".
I am running the function onClick generate pdf button (see: http://54.191.245.162:9080/forms/anon/org/app/f445e78b-fc77-4ef4-80f9-c82cfe207be8/launch/index.html?form=F_Form1)
this is my code on application start
app.getSharedData().loadScript = function (url, callback) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement("script")
script.type = "text/javascript";
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
then onNew form event I am passing the URL and callback function
var JSPDFurl = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js'
var jqueryURL = 'https://code.jquery.com/jquery-3.3.1.slim.min.js'
app.getSharedData().loadScript(jqueryURL, function () {
app.getSharedData().loadScript(JSPDFurl, function () {
function onClick() {
console.log('on click function is running')
console.log('JQUERY WORKING', $('.first-name input').val("jay chacko"))
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.canvas.height = 72 * 11;
pdf.canvas.width = 72 * 8.5;
pdf.fromHTML(document.body);
pdf.save('test.pdf');
};
var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);
})
})
For some reason the latest version of jsPDF is throwing error inside IBM FORMS, maybe an internal global scope conflict. version 1.2.60 and below seems to works fine and not throwing the above error.

inserting jquery into js file

I have a js file that in which i want to include jquery. in order to include the jquery script i am using this clode:
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
this works, I can see that incuded the script correctly. My inspector shows that it loaded the script but jquery wont work.
any ideas?
You need to make sure the script you are dynamically loading is actually loaded before attempting to use it.
To do so, use script.onload to fire a callback once the load is completed.
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head') [0].appendChild(script);
script.onload = function () {
/* jquery dependent code here */
console.log($);
};
MDN has an example that's more adaptable to a callback you specify -
// from https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement#Dynamically_importing_scripts
function loadError (oError) {
throw new URIError("The script " + oError.target.src + " is not accessible.");
}
function importScript (sSrc, fOnload) {
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.onerror = loadError;
if (fOnload) { oScript.onload = fOnload; }
document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
oScript.src = sSrc;
}
Your jQuery code is not working may be caused by jQuery is not loaded yet while browser executing your jQuery code. Use function below to dynamically load jQuery with callback. Put your jQuery code inside a callback function.
function loadScript(url, callback) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url;
if (typeof(callback) === 'function') {
s.onload = s.onreadystatechange = function(event) {
event = event || window.event;
if (event.type === "load" || (/loaded|complete/.test(s.readyState))) {
s.onload = s.onreadystatechange = null;
callback();
}
};
}
document.body.appendChild(s);
}
/* Load up jQuery */
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function() {
// Put your jQuery code here.
});
You need to include jQuery inside the HTML code. jQuery won't work for you because your script is loaded before jQuery is loaded.

Reload javascript resource programmatically in Chrome

I'm trying to reload javascript resources programmatically in Chrome and if I run that from console, then it works fine, but if I put that into the code to reload after an event was fired, then the resource doesn't change. What is the problem?
I use this reloader:
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = 'js/resource.js';
docHeadObj.appendChild(dynamicScript);
And here is the event handler:
obj.onclick(function(){
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = 'js/resource.js';
docHeadObj.appendChild(dynamicScript);
});
After both cases the new and proper <script> element is appended to the <head> and on network tab the resource is downloaded, but in case of the second one the resource is never change.
EDIT:
I'm closer to the problem. If I have this code in the resource which will be reloaded alert("aaa");
And I open the application then after performing a click event I get an alert with 3 'a' letter. Then I decrease the number of the letters to 2, reload the resource, perform a click event, then I again see 3 'a' letter. Then I decrease the number of letters to 1, save and click, then I see 2 'a' letter. So it seems to be the Chrome (and also FF) stores the last modified resource except if I reload that from console.
You should wait before the script is loaded before you use it. It can be achieved with using onload event for the dynamic script
function loadScript(url, callback) {
var docHeadObj = document.getElementsByTagName("head")[0];
var dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.src = url;
// bind the event to the callback function
dynamicScript.onreadystatechange = callback; //for ie<9
dynamicScript.onload = callback;
// Fire the loading
docHeadObj.appendChild(dynamicScript);
}
var testJQuery = function () {
console.log($(this));
};
var obj = document.getElementById("test");
obj.onclick = function () {
loadScript("//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js", testJQuery);
};
Working example on fiddle
If you just delete the last instance of the script tag before reloading it, that should force it to reload.
function load(link, id) {
var exists = document.getElementById(id)
if(exists){
exists.parentNode.removeChild(exists);
}
var script = document.createElement('script');
script.src = link;
script.id = id;
document.body.appendChild(script);
}
obj.onclick = function(){
load('js/resource.js','dynamicScript')
}

Javascript: Handle GET Error (document.createElement)

I'm trying to 'include' a JS file to my document. It works fine, but when the file is offline, it should set a variable to FALSE. I googled it, but I didn't get it. So I tried it with the try/catch:
try {
var jq = document.createElement('script');
//jq.onload = put;
jq.type = 'text/javascript';
jq.src = 'http://127.0.0.1:9666/jdcheck.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
catch(e) {
console.log('An error has occurred: '+e.message);
jdownloader = false;
}
It just throws me the error
Failed to load resource http://127.0.0.1:9666/jdcheck.js
How is it possible to set the var to FALSE?
Thank you,
Markus
You're sort of doing it wrong. When checking if a script source can be loaded, there are built in onload and onerror events, so you don't need try / catch blocks for that, as those are for errors with script execution, not "404 file not found" errors, and the catch part will not be executed by a 404 :
var jq = document.createElement('script');
jq.onload = function() {
// script loaded successfully
}
jq.onerror = function() {
// script error
}
jq.type = 'text/javascript';
jq.src = 'http://127.0.0.1:9666/jdcheck.js';
document.getElementsByTagName('head')[0].appendChild(jq);

Javascript added to head but unable to use it

I have a toggle switch that when i press it adds a Javascript to the head of the page:
function yourcallback (){
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'dev/additional_script.js';
head.appendChild(script);
}
Now when i use firebug to debug it i can see all of the scripts however if i try to call a function to that script it tells me that the function i am trying to call is undefined.
So it would seem that the script is not loaded correctly.
HOWEVER if i in firebug try and call the same function it returns function()
meaning that it should be defined.
Has anyone experianced anything like this and / or know how i can fix it.
please tell me if you need more code information and il add it to my question
update
Okay so here is the thing i have two scripts:
The script that controls the switch button (when the user press it another script will be loaded)
the script that is loaded when the script button is pressed ( this is where the function is located.
In script one i am trying to call a function in script 2 after it has been loaded and this is where i am getting the error:
The way i am calling the function is just using the function name
The function i am trying to access looks like this:
var init = function() {
var i, anchors, scriptTag;
//get the uid...
scriptTag = document.getElementById("link-replacer");
if(scriptTag) {
uid = scriptTag.getAttribute("data-uid");
} else {
uid = "none";
}
urlpart = forwardUrl+"?uid="+uid+"&url=";
if(doOnLoadReplace) {
anchors = document.getElementsByTagName("a");
for(i = 0; i < anchors.length; ++i) {
fixHref(anchors[i]);
}
}
};
Try this code
var myScript = document.createElement('script');
myScript.setAttribute('type', 'text/javascript');
myScript.setAttribute('src', 'dev/additional_script.js');
var headFirst = document.getElementsByTagName('head');
headFirst[0].appendChild(myScript);
I think you're adding the script incorrectly. Try this:
var newJS = document.createElement('script');
newJS.setAttribute('type','text/javascript');
newJS.setAttribute('src', 'dev/additional_script.js');

Categories