Dynamically loading an external JavaScript response - javascript

I'm using this code to include dynamically js file in run-time:
var headID = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.type='text/javascript';
script.src="js-debug/"+record.getId()+".js";
script.onload = function() {
inizializeComponent();
}
For every node of menu, I include a different js file.
Now I need to intercept the event triggered when the page does not exist to show a messagebox!
How can I get it?

Use script.onerror = function () { ....

Related

How to include dynamic Javascript file in the DOM without repeating same file

I want to load <div> content dynamically by using AJAX in a specific div. After the AJAX call I want to load a JS file in the footer. I loaded content by clicking menu without page loading by using URL hash. My problem is when I click the same link multiple times, the JS file is loading multiple times because the JS file is appended. That's why every event occurs multiple times. I want to load the JS file before checking if the file is already loaded into the DOM. If the file is not loaded in the DOM, I will append a JS file in the DOM.
As the answer suggested by this URL, here is my code:
var Utils = {
loadjs: function(url){
var footer = document.getElementsByTagName('body')[0];
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
footer.appendChild(script);
},
}
Utils.loadjs(url);
You can read the script tags to search for a particular script is there or not. Something like below:
var Utils = {
loadjs: function(url) {
var me = document.querySelectorAll('script[src="' + url + '"]');
if (me && me.length >= 1) {
return null;
}
var footer = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
footer.appendChild(script);
},
}
Utils.loadjs(url);
You can use dynamic import() syntax to load modules, even from regular scripts.
This has the benefit of loading those scripts as modules, which are always in strict mode and have module scope.
Read more about dynamic import
So, instead of Utils.loadjs(url), just import(url)

How do I access jQuery from a new window?

In my app I open a new window with var w = window.open(). I access the CanvasJS API with:
var canvas = w.document.createElement('script');
canvas.type = "text/javascript";
canvas.src = "https://canvasjs.com/assets/script/canvasjs.min.js";
w.document.head.appendChild(canvas);
This works perfectly fine. I did the same thing with jQuery and made sure to append it before my own script yet I get this error: ReferenceError: $ is not defined
Here is what my code looks like:
var w = window.open('','_blank',width,height);
w.document.body.innerHTML = '<body> //create chart container here </body>';
var jQuery = w.document.createElement('script');
var canvas = w.document.createElement('script');
var script = w.document.createElement('script');
canvas.type = "text/javascript";
canvas.src = "https://canvasjs.com/assets/script/canvasjs.min.js";
jQuery.type = "text/javascript";
jQuery.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";
script.textContent = "//my script content here, this is where I use the '$' jQuery object";
w.document.head.appendChild(jQuery);
w.document.head.appendChild(canvas);
w.document.head.appendChild(script);
Even though you have inserted the script tag in the head but this does not mean that the script have been downloaded completely. You code runs before the browser is able to download jQuery. Dynamically inserted script tags perform async operation.
I suggest that you setup an interval and check if jQuery is available. Once it is available execute your code. Name the script element created for jQuery something else as it will interfere with checking for jquery within your interval.
var jqueryCheck = setInterval(function() {
if(window.jQuery) {
clearInterval(jqueryCheck);
// execute your code
}
}, 100);

phonegap - dynamically adding javascript

Developing phonegap application which loads google map. Using below two javascript for google map. One javascript is loaded from locally while other javascript loaded from server.
var script = document.createElement('script');
script.src = 'http://maps.google.com/maps/api/js?sensor=true';
script.type = 'text/javascript';
document.head.appendChild(script);
script.onload = function () {
var script1 = document.createElement('script');
script1.src = 'js/jquery.ui.map.js';
script1.type = 'text/javascript';
document.head.appendChild(script1);
script1.onload = function () {
alert(google.maps.LatLng);
}
};
Both javascripts should be loaded after html page is loaded. Tried below code and referred various blogs, but its not working.
If same scripts written in header tag of html page, then it working perfectly. but in my application i need it to be loaded dynamically.
Please help....
Solved:
var doc_write = document.write; // Remember original method;
document.write = function(s) {$(s).appendTo('body')};
$.getScript('http://maps.google.com/maps/api/js?sensor=true').done(function()
{
$.getScript('js/jquery.ui.map.js').done(function()
{
document.write = doc_write; // Restore method
setTimeout(function()
{
alert(google.maps.LatLng);
},1000);
})
.fail(function(jqxhr, settings, exception)
{
alert(exception); // this gets shown
document.write = doc_write; // Restore method
});
}).fail(function()
{
alert('failed to load google maps');
});
Problem:
It takes some time to initialise.
Call your javascript function after device get ready function. Because if you are using phone gap through Xcode, the device get ready function take some time to load and your script is called before it.
Don't do it in this way
Load it in footer section of your application

Making sure same javascript files are not downloaded multiple times

I am trying to develop an embeddable widget. This widget renders some UI elements into the customer's page.
This widget will look like this:
<script src="//example.com/widget.js?param1=a&param2=b" async></script>
A user is allowed to embed multiple widgets on a single page, each with a different set of parameters.
Within this widget script, I am trying to load other javascript and css files required to render my widget.
This is the function I am using to load other javascript files.
function loadScript(scriptUrl) {
var s = document.createElement('script');
s.async = true;
s.src = scriptUrl;
document.body.appendChild(s);
}
The problem is that each script loaded this way is loaded multiple times, when there are more than one embeds per page.
How do I make sure each file is loaded only once?
For example, I try to load a jQuery reference inside that loader script, I see that if I embed my widget 5 times, there are 5 calls to the jquery library.
3 extra lines of code
var scripts = {}; //record what is loaded
function loadScript(scriptUrl) {
if (scripts[scriptUrl]) return; //exit if loaded
scripts[scriptUrl] = 1; //mark that it is loaded
var s = document.createElement('script');
s.async = true;
s.src = scriptUrl;
document.body.appendChild(s);
}

Method to see jQuery files are loaded completely then execute the function related to it

Method to see jQuery files are loaded completely then execute the function related to it
I want to show my div only when all the jQuery files related to that div is loaded.
document ready and window load function doesn't work.
How to write a conditional function where u can check whether all the jQuery is loaded then show the div.... i am calling all my jQuery files in an external js file, (basically i am trying to create a plugin for my client so that my external.js file will work from my server remotely).
my external.js file goes like this:
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'js/jquery-1.7.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'js/fancybox.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
}
document.ready = function() {
$(document).ready(function(){
$("#addimage").html("<a id='fancybox' href='large"+clientID+".jpg'><img border=0 src='thumb"+clientID+".jpg'/></a>");
}
});
so i want this addimage div work only my jquery files is loaded completely
use
if (jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}

Categories