Dynamic google javascripts loading failing - javascript

I have several listeners on modals that look like this:
$('#modaledithistory').on('shown.bs.modal', function() {
loadjscssfile("js/editable_table.js", "js", function(){ setHistory(true); });
});
The function being called is:
function loadjscssfile(filename, filetype, callback){
if (filesadded.indexOf("["+filename+"]")==-1){
if (filetype=="js"){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
fileref.onreadystatechange = callback;
fileref.onload = callback;
}
if (typeof fileref!="undefined"){
// Fire the loading
document.getElementsByTagName("head")[0].appendChild(fileref);
console.log("added to html: " + filename);
}
filesadded+="["+filename+"]";
} else {
window[callback]();
console.log("already loaded: " + filename);
}
console.log(callback);
}
This works just fine and as expected.
The problem happens with this listener:
$('#modalreporting').on('shown.bs.modal', function() {
loadjscssfile("https://www.gstatic.com/charts/loader.js", "js", null);
loadjscssfile("js/graphs.js", "js", function(){ initGraphs(); drawGraphs(); mobileRotateScreen(true);
} );
The console errors I get from this don't make any sense considering the code with the callback actually states to wait until the file is completely loaded BEFORE executing code.
Errors:
graphs.js:20 Uncaught ReferenceError: google is not defined
at graphs.js:20
graphs.js:313 Uncaught TypeError: Cannot read property 'DataTable' of undefined
at drawGaugegraph (graphs.js:313)
at drawGraphs (graphs.js:49)
at HTMLScriptElement.onreadystatechange (javascript.js:1030)
The lines generating the errors:
// line 20
google.charts.load('current', {
packages: ['corechart']
});
// line 313
var data = new google.visualization.DataTable(),
max = 0;
So what the console is saying is that the object 'google' doesn't exist.
The file however, should be loaded. I went through it and there isn't even a google object created in there.
When placing the script element directly in the html it works, but for performance reasons I'd rather not do that.
Can anyone help me make sense of this?
Thx!
EDIT:
I noticed the window[callback](); also isn't working as it should be.
On doing that line I get javascript.js:1011 Uncaught TypeError: window[callback] is not a function.

first, try waiting for the google charts script to load, before loading the next script...
$('#modalreporting').on('shown.bs.modal', function() {
loadjscssfile("https://www.gstatic.com/charts/loader.js", "js", function () {
loadjscssfile("js/graphs.js", "js", function() {
initGraphs();
drawGraphs();
mobileRotateScreen(true);
});
});
});
next, you need to wait for google's load statement to finish,
before using the google.visualization namespace...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable(),
max = 0;
...
});

Disclaimer: in order to be able to make a long comment and add formatting I need to post an answer.
I adapted it a bit, cause the 3 functions after the loading of the JS file actually call the datatable etc and need to be re-executable (hence window[callback](); in loadjscssfile).
$('#modalreporting').on('shown.bs.modal', function() {
loadjscssfile("https://www.gstatic.com/charts/loader.js", "js", function () {
loadjscssfile("js/graphs.js", "js", function() {
console.log("loaded graphs2");
initGoogleLibraries("googleCharts").then(function () {
initGraphs();
drawGraphs();
mobileRotateScreen(true);
});
});
});
});
graphs.js
function initGoogleLibraries(googleLib) {
if (filesadded.indexOf("["+googleLib+"]")==-1){
google.charts.load('current', {
packages: ['corechart','gauge']
}).then(function () {
filesadded+="["+googleLib+"]";
console.log("loaded google Lib");
});
} else {
return;
}
}
The then is giving issues.
Uncaught TypeError: Cannot read property 'then' of undefined at HTMLScriptElement.onreadystatechange
Basically the logic behind it should be:
Click modal
Load JS files
When JS loaded, load the google 'corechart' and 'gauge' libraries
When libraries loaded execute initGraphs(), drawGraphs() and mobileRotateScreen(true)
When modal is closed and clicked again only initGraphs(), drawGraphs() and mobileRotateScreen(true) should be executed again (because loading the js all over again would be even less performant than it was before.

Related

Odoo pos ReceiptScreenWidget _super() functionality not working properly

I have included some functionionality for ReceiptScreenWidget(using _super()) in my custom module, so that i can include some more logic in that function. But it is executing only after page load.
How to make it work along with the actual function.
Here is the code:
odoo.define('extended.screens', function (require) {
var screens = require('point_of_sale.screens');
screens.ReceiptScreenWidget.include({
show: function() {
this._super();
console.log("inside show custom>>>");
}
});
})
Now the "inside show custom>>>" message is printing in console only after page load.

CkEditor - Uncaught TypeError: Cannot read property 'getSelection' of undefined

I am implementing the CKEditor in my app. When I am trying to instantiate CKEditor to the textarea I am getting following error
Cannot read property 'getSelection' of undefined
at below line of ckeditor
getNative: function() {
return void 0 !== this._.cache.nativeSel ? this._.cache.nativeSel : this._.cache.nativeSel = B ? this.document.$.selection : this.document.getWindow().$.getSelection() }
Any help is much appreciated.
I have a list of articles.
every time I clicked on any article a "dialog / modal" should be open.
in such dialog or modal there was a ckeditor element for the content of my article.
when I clicked on the first it worked like a charm.
the problem was after clicking on the 2nd, 3rd, 4th etc.
Then I started to have this error.
TypeError: Cannot read property 'getSelection' of undefined
at CKEDITOR.dom.selection.getNative (ckeditor.js:448)
at new CKEDITOR.dom.selection (ckeditor.js:446)
at a.CKEDITOR.editor.getSelection (ckeditor.js:443)
at new CKEDITOR.plugins.undo.Image (ckeditor.js:1182)
at CKEDITOR.plugins.undo.UndoManager.save (ckeditor.js:1177)
at a.<anonymous> (ckeditor.js:1173)
at a.n (ckeditor.js:10)
at a.CKEDITOR.event.CKEDITOR.event.fire (ckeditor.js:12)
at a.CKEDITOR.editor.CKEDITOR.editor.fire (ckeditor.js:13)
at a.setData (ckeditor.js:275)
The solution for me was easy, tell the computer to destroy the ckeditor instance when the dialog / modal is closed. easy!..
Now is working like a charm =)
$mdDialog.show({
parent: parentEl,
targetEvent: $event,
templateUrl: '/md-templates/blog-article.html',
controller: DialogController,
scope: $scope,
preserveScope: true,
onRemoving: function (event, removePromise) {
if (CKEDITOR.instances.body) CKEDITOR.instances.body.destroy();
}
});
I got same error, and I solved by initialize CKEditor, in
$(document).function(ready());
$(document).ready(function () {
CKEDITOR.replace('editor1', {
language: 'tr',
height: '300'
});
});
I think when you initialize before page load, it doesn't find dom element(textarea)
This is likely your application is attempting to access and set the data of the CKEditor before the editor is ready. This can be the result of a race condition, causing the error to be intermittent. There are a few things you can do to prevent this issue.
First, the CKEditor endorsed method of testing if the editor is loaded first.
if ( CKEDITOR.status == 'loaded' ) {
// The API can now be fully used.
doSomething();
} else {
// Wait for the full core to be loaded and fire its loading.
CKEDITOR.on( 'load', doSomething );
CKEDITOR.loadFullCore && CKEDITOR.loadFullCore();
}
Second, if you are unable to control the timing associated with setting of the editor value, you could wrap the CKEDITOR.dom.window object in an async/await Promise that tests if the editor is loaded first, and if not, listens for the editor to load, and then complete setting the value. (note, this code is not fully tested)
CKEDITOR.dom.window = (function(window) {
if ( CKEDITOR.status == 'loaded' ) {
// The API can now be fully used.
return window;
} else {
return (async function() {
return await function() {
return new Promise(resolve => {
CKEDITOR.on( 'load', () => {
resolve(window);
});
});
};
})();
CKEDITOR.loadFullCore && CKEDITOR.loadFullCore();
}
})(CKEDITOR.dom.window);
You can have a try
CKEditor.destroy();
change the function f.$.onload inside ckeditor.js to the below
f.$.onload=function(){var toutMs =5000;
if(CKEDITOR.document.getHead().$.childElementCount > 6)
{
toutMs=0;
}
setTimeout(function(){
A(b,!0)
},toutMs)
}

Using spinnerPlugin on page load is giving error.

I have 2 pages. Index.html and detail.html. On index.html, when I click login, I call this function
$('form').submit(function (event) { //Trigger on form submit
var options = { dimBackground: true };
SpinnerPlugin.activityStart("Loading...", options);
});
It works perfectly. But on detail.html, I call this
$(document).ready(function () {
var options = { dimBackground: true };
SpinnerPlugin.activityStart("Loading...", options);
});
And it gives me the following error.
Uncaught ReferenceError: SpinnerPlugin is not defined
I have installed the SpinnerPlugin using xml as well. Wat should I do? Why is it working on index.html and not on detail.html?
Spinner plugin will only be available after the device ready event. This means that you should wrap your code with it:
$(document).ready(function () {
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
var options = { dimBackground: true };
SpinnerPlugin.activityStart("Loading...", options);
}

How do I get javascript to run when pdfjs is loaded?

Trying to auto-search with pdfjs, (and having hard time with the docs..)
THIS WORKS:
<input type="button" value="click-me" onclick="searchPDF('cpu');" />
THIS DOESN'T (jquery running ok)
$(document).ready(function() {
searchPDF('cpu');
});
HOW DO SUSPEND EXECUTION UNTIL THE PDF IS PARSED? (OR WHY ISN'T IT WORKING)
MODIFIED viewer.html (thanks to PDF.js - Using search function on embedded PDF )
// search with PDF.js
function searchPDF(td_text) {
//PDFView.findBar.open();
$('#findInput').val(td_text);
$("#tableDiv").focus();
PDFView.findBar.findNextButton.click();
var event = document.createEvent('CustomEvent');
event.initCustomEvent('find', true, true, {
query: td_text,
caseSensitive: $("#findMatchCase").prop('checked'),
highlightAll: $("#findHighlightAll").prop('checked'),
findPrevious: undefined
});
return event;
Finally found a solution for us that doesn't digest javascript for breakfast:
(thanks to
Based on viewer.html and added jquery:
$(document).ready(function() {
document.addEventListener('textlayerrendered', function (e) {
if (e.detail.pageNumber === PDFView.page) {
// finished rendering, call a JS-function..
searchPDF('cpu');
}
}, true);
});
function searchPDF(str) {
alert('working');
..add code from
http://stackoverflow.com/questions/38976490/how-do-i-get-javascript-to-run-when-pdfjs-is-loaded
}

jquery image load check error

i'm trying to check if all images are loaded within a container using the below code
$(document).ready(function () {
$(".slide img").each(function (index) {
var fakeSrc = $(this).attr('src');
$("<img/>").attr("src", fakeSrc).css('display', 'none').load(function () {
alert('loaded');
}).
error(function () {
load_img_Single(fakeSrc);
});
});
function load_img_Single(img) {
alert(img);
var ruth;
$("<img/>").attr("src", img).css('display', 'none').load(function () {
ruth = 'yeap';
}).error(function () {
ruth = 'nope';
});
alert(ruth);
}
});
now as u can see im using a fake container to load the image and check if it has been loaded or not .
im using the .error in the first check of image to see if it was loaded properly or not , if not it executes the function load_img_Single(image) function of mine to load it again.
now in that function again im checking if it was loaded or not . but the problem is the variable 'ruth' is not getting set to anything within that function. its been declared outside but still its coming as 'undefined'.
any insight would be appreciated guys.
The reason is loading image is asynch. When you call:
$("<img/>").attr("src", img).css('display', 'none').load(function() {
ruth = 'yeap';
}).error(function() { ruth = 'nope'; });
The load or error do not fire yet. That's why ruth is undefined when you call alert(ruth); right after that

Categories

Resources