Catch exception in dynamically added scripts in ReactJs - javascript

I have a function that adds an external script dynamically. here is my code
try {
const script = document.createElement('script');
script.src = 'script url';
script.async = isAsync;
document.body.appendChild(script);
} catch(e){
console.log(e);
}
but when exception occurs in the script, try catch not catching that error. Also my code is inside react error boundary but still my react app crashes on script error.

Related

Marketo Form Embed to Vue JS Application

I'm trying to add a Marketo form to my Vue Js application but it doesnt seem to be working.
I loaded the initial forms2.min.js script in the created lifecycle hook and that loads just fine. Example code below.
created() {
const scriptTag = document.createElement('script');
scriptTag.src = "//app-ab00.marketo.com/js/forms2/js/forms2.min.js";
scriptTag.setAttribute('charset', 'utf-8');
document.head.appendChild(scriptTag);
}
Within the html template i added the container element to load the form.
<form id="mktoForm_1057"></form>
Then i created a method that gets triggered by a button to load the form into the container.
createForm(){
MktoForms2.loadForm("//app-ab00.marketo.com", "785-UHP-775", 1057)
}
As soon as i run the script i get this error "MktoForms2 is not defined." Am i doing something wrong?
Would someone be able to help me out?
Thanks!
It should be
created() {
const scriptTag = document.createElement('script');
scriptTag.src = "//app-ab00.marketo.com/js/forms2/js/forms2.min.js";
scriptTag.setAttribute('charset', 'utf-8');
scriptTag.onload = function() {
MktoForms2.loadForm("//app-ab00.marketo.com", "785-UHP-775", 1057);
};
document.head.appendChild(scriptTag);
}
It's hitting a snag because MktoForms2 is not defined as a variable. I had to append 'window' to MktoForms2 in order for it to pass linting
window.MktoForms2.loadForm('//app-ab00.marketo.com', '785-UHP-775', 1057)
Here is a little snippet I have used for Marketo templates. Make sure you have their forms2.min.js file loaded before using this script. You could also wrap this in a DOM ready/jQuery ready as well.
// check if we have their forms2.min.js script available
if (window.MktoForms2) {
// error handling
try {
MktoForms2.loadForm(baseUrl, munchkin_id, formId, function(form) {
// code to execute after load form
});
MktoForms2.whenRendered(function(a) {
// code to execute after the form has rendered its markup
var fid = a.getId(); // form id
});
} catch (a) {
console.log(a);
}
}

The page failed to load my scripts module after finishing to load

I create the script tag and append it on the document with the event of loading so that the page when finishes to load it will execute my script but i'm i'm facing with the problem where the page didn't load my script and didn't drop the error to my scripts code looks like this
window.addEventListener('load',() => {
script = document.createElement('script');
script.type = 'module';
script.src = 'custom.js';
document.body.appendChild(script);
});
but i doesn't work for me
check up if you are doing this over local host connection because the module didn't run without the connection or you the problem might be in your browse if you are using IE 7 or earlier but the solution of the IE 7 or earlier is this
if (window.addEventListener) {
window.onload = scriptFunction();
} else if (window.attachEvent){
window.onload = scriptFunction();
}
function scriptFunction() {
script = document.createElement('script');
script.type = 'module';
script.src = 'custom.js';
document.body.appendChild(script);
}

How to run code (Google/Doubleclick Ads) without block main thread

Is there any way to run Google Ads code without block main thread? Google Pagespeed Insights shows me a warning "Reduce the impact of third-party code": Third-party code blocked the main thread for ...
Third-Party Size Main-Thread Blocking Time
Google/Doubleclick Ads 193 KB 253 ms
I've placed a script to the end of the page in the footer.
<script data-ad-client="ca-pub-xxx" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
I tried to add "data-aload data-original=..." but it doesn't help. Maybe it would a right choice to use requestAnimationFrame() or setTimeOut(), but I don't know how to implement it on this.
You can add script dynamically. NB there is no need to add async since browser considers all dynamic script async by default
const loadScript = (src, id, callback) => {
const script = document.createElement('script');
script.src = src; // URL for the third-party library being loaded.
script.id = id; // e.g., googleMaps or stripe
script.defer = true; // make sure that browser will run script after page loaded
document.body.appendChild(script);
script.onload = () => {
if (callback) callback(); // conditional callback
};
};

Is dynamic script injection in html blocking?

In this question it is clearly shown how to programmatically inject a new script in an HTML page.
What I'd like to ask, however, is if such injection is blocking, that is, it'll wait for the injected script to be loaded and executed before calling the next line.
For example
function inject(script_url) { ... }
// somewhere in the code
inject('/path/to/script.js');
func_in_script(); // <-- will "func_in_script" be defined at this point?
EDIT:
This is what I found out trying:
If I use native JS like
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = false; // !!!
script.defer = false; // !!!
document.head.appendChild(script);
Then the functions in the loaded script are not immediately available after the call to appendChild(); however if I use jQuery like:
$('<script/>', {
type: 'text/javascript',
src: url,
async: false,
defer: false
}).appendTo('head');
It works as I'd like it to.

JavaScript dynamic loading

I have senerio, where I need to render my HTML page by using dynamic JavaScript.
I am using loadScript function to load external JavaScript and passing callback funtion. In my HTML page , I am loading this script for my header.
My header section is working perfectly after the script is loaded and I my head section I can see my new script.
However , when I am trying to use the variables from this script its undefined.
function loadScript(url,callback){
var script = document.createElement("script");
script.type = "text/javascript";
script.id="acvDataRequest";
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
alert(dataHeader) // I CAN SEE MY OBJECT FROM LOADED SCRIPT
callback();
};
}
script.src = url;
alert(dataHeader); // IT SAYS UNDEFINED
}
calling a script using :
var actionName ="JSONdata/json.js";
loadScript(actionName,mergeTemplateJSONScript);
Please advice , why i can't see my variables even if my script is there.
Inside script.onload , I am able to see my variable but not outside
The line script.src = url; triggers the loading of the script file. If you call alert immediately after it your external script has not been loaded yet. You can only access variables from the json once the onreadystatechange or onload functions have been called.
What you should do is using it like this:
var actionName ="JSONdata/json.js";
loadScript(actionName,function(){
alert(dataHeader);
});
What you assign:
script.src = url;
that just starts the loading of the dynamic script. When you call the second alert() on the very next line your script has not yet loaded (it is loading in the background at that point). You can only reliably access the variables from the newly loaded script from within the onload handler or in some function called from the onload handler.
Keep in mind that the dynamic loading of scripts is asynchronous. That means it happens in the background while other scripts keep running (thus your second alert() runs before the script has finished). And, then the script finishes loading some time later and when it does the onload handler is called.
So, when you dynamically load scripts, all code that uses those scripts needs to either be in the onload handler, in some function called from the onload handler or guarenteed not to execute until some time later (such as in an event handler that you're sure won't happen before the script finishes loading).
To explain further, I've added some annotations to your code:
function loadScript(url,callback){
var script = document.createElement("script");
script.type = "text/javascript";
script.id="acvDataRequest";
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
// ** your script is now loaded here **
alert(dataHeader) // I CAN SEE MY OBJECT FROM LOADED SCRIPT
callback();
};
}
script.src = url;
// ** your script is in the process of loading here and has likely not completed **
alert(dataHeader); // IT SAYS UNDEFINED
}

Categories

Resources