zopim callback is never called - javascript

Following the instruction of the this documentation, I end up with the following code:
window.zEmbed || (function (d, s) {
var z = $zopim = function (c) { z._.push(c) },
$ = z.s =
d.createElement(s), e = d.getElementsByTagName(s)[0]; z.set = function (o) {
z.set.
_.push(o)
}; z._ = []; z.set._ = []; $.async = !0; $.setAttribute("charset", "utf-8");
$.onload = (event) => {
console.log("chat script has loaded");
};
$.src = "//v2.zopim.com/?#zopimClientID"; z.t = +new Date; $.
type = "text/javascript"; e.parentNode.insertBefore($, e);
})(document, "script");
var onChatStart = function () {
$zopim.livechat.window.show();
window['onChatStart'] && window['onChatStart']();
};
$zopim(function () {
$zopim.livechat.clearAll();
(......)
});
The problem is that the $zopim(funtion() {..}) callback function is never called, but the script is successfully loaded. I know based on the console.log made by:
$.onload = (event) => {
console.log("chat script has loaded");
};
Any one knows why this is happening?
Thank you

The problem is you're running the $zopim script before it's fully loaded. Once all the parts of the $zopim object have loaded it will stop looping and run your script.
var zopimConfig = function() {
$zopim(function() {
$zopim.livechat.clearAll();
(......)
});
};
var waitForZopim = setInterval(function () {
if (
window.$zopim === undefined ||
window.$zopim.livechat === undefined ||
window.$zopim.livechat.departments === undefined
) {
return;
}
zopimConfig();
clearInterval(waitForZopim);
}, 100);
Waiting for window.$zopim.livechat.departments is optional, however if you're doing anything around departments I would recommend keeping this

Related

javascript DOM object (window) extended property is null on page reload after being idle

I have a custom extended property attached to the window object in JavaScript as follows:
Community.js
(function (window, document, $) {
'use strict';
var containerScrollPositionOnHideList = [];
var scrollToTopOnShowContainerList = [];
var userProfileInfo = {};
window.Community = $.extend({
//init
init: function () {
var Site = window.Site;
Site.run();
this.enableHideShowEventTrigger();
},
setUserInfo: function (userObj) {
if (UtilModule.allowDebug) { debugger; }
window.localStorage.setItem('userInfo', JSON.stringify(userObj));
var d = new $.Deferred();
$.when(this.initUserProfile(userObj.UserId)).done(function () {
d.resolve("ok");
});
},
getUserInfo: function () {
var userJson = window.localStorage.getItem('userInfo');
var userObj = JSON.parse(userJson);
return userObj;
},
})(window, document, jQuery);
The problem is that this extension property window.Community is null in certian scenarios when i refresh the page which i am going to describe below along with flow of code.
and here is a module in JavaScript to force reload scripts even if they are cached every time the page is refreshed as my code heavily depends on javascript calls so I just enabled it to make sure while I am still writing the code page reloads every time, the code is below as follows:
Util.js
var UtilModule = (function () {
var allowDebug = false;
var currentVersion = 0;
var properlyLoadScript = function (scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function () {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript(scriptPath)).done(function () {
callBackAfterLoadScript();
d.resolve("ok");
});
}
else {
console.log('Community loaded already and running now : ' + scriptPath);
callBackAfterLoadScript();
}
return d.promise();
};
var forceReloadScript = function (scriptPath) {
if (UtilModule.allowDebug) { debugger; }
var d = $.Deferred();
initCurrentVersion();
var JSLink = scriptPath + "?version=" + currentVersion;
var JSElement = document.createElement('script');
JSElement.src = JSLink;
JSElement.onload = customCallBack;
document.getElementsByTagName('head')[0].appendChild(JSElement);
function customCallBack() {
d.resolve("ok");
}
return d.promise();
};
var enableDebugger = function () {
allowDebug = true;
};
var disableDebugger = function () {
allowDebug = false;
};
var debugBreakPoint = function () {
if (allowDebug) {
}
};
var initCurrentVersion = function () {
if (currentVersion == 0) {
var dt = new Date();
var ttime = dt.getTime();
currentVersion = ttime;
}
};
var getCurrentVersion = function () {
return currentVersion;
};
return {
forceReloadScript,
properlyLoadScript,
enableDebugger,
disableDebugger,
debugBreakPoint,
allowDebug,
getCurrentVersion
};
})();
Note: I have made deferred objects to resolve only when the JSElement.onload has been called successfully. This step was taken just for testing purpose to make sure that I am not missing something before reaching a point to call the method where I am getting an error.
After that the code where I load scripts using UtilModule in my layout file look like as below:
_Layout.cshtml
<script src = "~/Scripts/Application/Modules/Util.js" ></script>
<script>
$.when(
UtilModule.properlyLoadScript('/Scripts/Application/Community.js', () => {
// Community.init() was supposed to be called here but i was still getting the error so i implemented this using promise that is returned from properlyLoadScript and call Community.init() further in .done callback to make sure that script is properly loading till this point.
//window.Community.init();
})
).done(function() {
window.Community.init();
});
</script>
#RenderSection("scripts", required: false)
Now coming to my main file where My index file is executing having (_layout.chsmtl) as parent layout
is
Index.cshtml
#{
ViewBag.Title = "My Blog";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<article id="BlogPage" style="margin: 5px;">
</article>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$.when(UtilModule.properlyLoadScript('/Scripts/Application/Modules/Blog.js', () => {
})).done(function () {
BlogModule.init();
});
});
//});
</script>
}
from what I know is that #section scripts is executed only once all the scripts in the layout page are loaded first so seems like a safe place to initialize the code which is dependent on some script in _Layout.HTML file and further enclosed with $(document).ready() for testing just to make sure that this script loads after everything else is loaded already.
Note: I am running all this code in in-cognito mode in chrome so nothing is cached while this code is running
now my Blog.js file looks like as below
var BlogModule = (function () {
var moduleReference = this;
var PageId = "#BlogPage ";
var currentUser;
var BlogPostList = [];
var blogPostInfo = {};
//init
var init = function () {
if (UtilModule.allowDebug) { debugger; }
//This is where the problem happens
console.log(window.Community);
console.log(window.Community.getUserInfo());
currentUser = window.Community.getUserInfo();
initBlogInformation();
//window.Community.registerModule(BlogModule);
if (Object.keys(window.Community.getUserProfileObject()) <= 0) {
$.when(window.Community.initUserProfile(currentUser.UserId)).then(function () {
$.when(initBlogInformation()).done(function () {
//debugger;
console.log(BlogPostList);
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
});
}
else {
$.when(initBlogInformation()).done(function () {
window.WidgetManager.populateWidget(PageId, moduleReference);
loadBlogPostWidget();
loadBlogViewWidget();
loadBlogCommentsWidget();
});
}
};
var loadBlogIndexMenuWidget = function () {
if (UtilModule.allowDebug) { debugger; }
};
var loadBlogPostWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogPostWidget";
widgetOptions.container = PageId + "#BlogPostWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
}
var loadBlogViewWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogViewWidget";
widgetOptions.container = PageId + "#BlogViewWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var loadBlogCommentsWidget = function () {
var widgetOptions = {};
widgetOptions.type = "BlogCommentsWidget";
widgetOptions.container = PageId + "#BlogCommentsWidgetContainer";
var settings = {};
settings.UserId = 1;
widgetOptions.settings = settings;
window.WidgetManager.loadWidget(widgetOptions);
};
var initBlogList = function () {
$.when(getBlogPosts()).then(function (results) {
if (UtilModule.allowDebug) { debugger; }
BlogPostList = results.Record;
console.log(BlogPostList);
});
};
var getBlogPosts = function () {
if (UtilModule.allowDebug) { debugger; }
var d = new $.Deferred();
var uri = '/Blog/GetBlogPosts?userId=' + currentUser.UserId;
$.post(uri).done(function (returnData) {
if (UtilModule.allowDebug) { debugger; }
if (returnData.Status == "OK") {
BlogPostList = returnData.Record;
BlogPostList.map(x => {
if (UtilModule.allowDebug) { debugger; }
x.UserName = window.Community.getUserProfileObject().UserName;
if (x.Comments != null) {
x.CommentsObject = JSON.parse(x.Comments);
x.CommentsCount = x.CommentsObject.length;
}
});
console.log(returnData.Record);
d.resolve("ok");
} else {
window.Community.showNotification("Error", returnData.Record, "error");
d.resolve("error");
}
});
return d.promise();
};
var initBlogInformation = function () {
//debugger;
var d = $.Deferred();
getBlogPosts().then(getBlogModelTemplate()).then(function () {
d.resolve("ok");
});
return d.promise();
};
//Get Blog Model
var getBlogModelTemplate = function () {
var d = new $.Deferred();
var uri = '/Blog/GetBlogModel';
$.post(uri).done(function (returnData) {
blogPostInfo = returnData.Record;
d.resolve("ok");
});
return d.promise();
};
return {
init: init,
};
})();
The error I have highlighted below
so the problem is in init function of BlogModule which is BlogModule.init() the page is idle for too long and I reload it I get the following error:
cannot call
window.Community.getUserInfo() of undefined implying that community is undefied
after couple of refreshes its fine and the issue doesn't happen unless I change reasonable portion of code for js files to be recompiled again by browser or the browser is idle for too long and I am not able to understand what is triggering this issue.
below is log from console
p.s. error occurs more repeatedly if i refresh page with f5 but happens rarely if i refresh page with ctrl + f5
Please any help would be of great value
Answering my own question, took a while to figure it out but it was a small mistake on my end just fixing the following function in Util.js fixed it for me
var properlyLoadScript = function(scriptPath, callBackAfterLoadScript) {
//get the number of `<script>` elements that have the correct `src` attribute
//debugger;
var d = $.Deferred();
$('script').each(function() {
console.log($(this).attr('src'));
});
if (typeof window.Community == 'undefined') {
//debugger;
console.log('community was undefined till this point');
//the flag was not found, so the code has not run
$.when(forceReloadScript('/Scripts/Application/Community.js')).done(function() {
//debugger;
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
d.resolve("ok");
});
} else {
console.log('Community loaded already and running now : ' + scriptPath);
$.when(forceReloadScript(scriptPath)).done(function() {
callBackAfterLoadScript();
});
}
return d.promise();
};

Is JS 'load' event on script guarantee full script loading?

I had a trouble with script element async loading guarantees.
When 'load' callback was called on a page with a lot of other scripts, the global variable, which should be defined in external script, was not yet available. On the other hand, after some timeout it became visible. You can see example of how I am doing it:
function async(u, c) {
var d = document, t = 'script',
o = d.createElement(t),
s = d.getElementsByTagName(t)[0];
o.async = true;
o.src = '//' + u;
if (c) { var once = false;
o.addEventListener('load', function (e) { if (!once) { once = true; c(null, e); }}, false);
o.onreadystatechange = function () {
//for IE <= 8
if (this.readyState == "complete" || this.readyState == "loaded") {
if (!once) { once = true; c(null, e); }
}
}; }
s.parentNode.insertBefore(o, s);
};
async("cdnjs.cloudflare.com/ajax/libs/ifvisible/1.0.6/ifvisible.min.js", function() {
var f = function() {
var activeSent = false;
// We detected that sometimes ifvisible is actually undefined !!!
if (typeof ifvisible != 'undefined') {
ifvisible.on('wakeup', function () {
if (!activeSent) {
activeSent = true;
console.log("I detected this move.")
}
});
ifvisible.idle();
} else {
console.log("not init.")
}
};
f();
});
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<p id="me">
Just move on ME with your mouse
</p>
My question - is there a strong or relaxed guarantee that after 'load' callback is invoked, the script was actually fully loaded on the page? Thank you.

Nested function not work in Mozilla browser

i have call the below function in my application
function workerCall() {
debugger;
if (typeof (Worker) !== "undefined") {
var worker = new Worker("Scripts/worker.js");
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
worker.postMessage({ 'username': Username });
function workerResultReceiver(e) {
$('.NotificationCount').html(e.data);
if (parseInt(e.data) != 0 && currentPage == "Alert") {
StateFlag = false;
$('.Notification').show();
$('.Drildown').each(function () {
var temp = this.id;
if ($('#' + temp).attr('expand') == "true") {
currentTab = temp;
StateFlag = true;
}
});
currentScrollPosition = $('body').scrollTop();
GetAlerts();
} else {
$('.Notification').hide();
}
}
function workerErrorReceiver(e) {
console.log("there was a problem with the WebWorker within " + e);
}
}
else {
}
}
the method will execute in IE,Chrome but when comes to Mozilla i got an error ReferenceError: workerResultReceiver is not defined.How can i resolve this error?
This happens because you are making reference to function that is not created yet. You need to put this:
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
Above
function workerErrorReceiver
line or at the end of the scope.

javascript scoping in requirejs and qunit

I've been trying to puzzle out why the scoping was a little screwy on these 2 prototype objects - the first one is my preloader based on PreloadJS and the second is my QUnit test. I've fixed the issue but I accidently deleted the original thread which someone kindly responded to so I've reposted this working version to say thankyou to that person
'use strict';
define(['preloadjs'], function (PreloadJS) {
var Preloader = function (model) {
this.model = model;
this.totalLoaded = 0;
this.context = model.context;
this.isFinished = false;
this.onStart = (model.onStart != null) ? model.onStart : function (e) {};
this.onUpdate = (model.onUpdate != null) ? model.onUpdate : function (e) {};
this.onComplete = (model.onComplete != null) ? model.onComplete : function (e) {};
this.preload = null;
// make sure assets exists
if (model.assets == null) {
model.assets = {};
}
this.init();
};
/**
* initialise preloader
* #return {null}
*/
Preloader.prototype.init = function() {
var self = this;
var preload = new PreloadJS();
if (this.onStart != null) {
this.onStart();
}
preload.onProgress = function (e) { self.onUpdate(e); };
preload.onComplete = function (e) { self.handleComplete(e); };
preload.onFileLoad = function (e) { self.onFileLoad(e); };
preload.loadManifest(this.model.manifest);
this.preload = preload;
};
Preloader.prototype.handleComplete = function(e) {
this.isFinished = true;
this.onComplete(e);
};
/**
* called when each file in the manifest is loaded - if it's an image,
* create an image object and populate its properties
* #param {event} e event object
* #return {null}
*/
Preloader.prototype.onFileLoad = function(e) {
if (e.type == PreloadJS.IMAGE) {
var self = this;
var img = new Image();
img.src = e.src;
img.onload = function () { self.handleFileComplete(); };
this.model.assets[e.id] = img;
}
};
/**
* iterates totalLoaded when each image has intialised
* #return {null}
*/
Preloader.prototype.handleFileComplete = function() {
this.totalLoaded++;
};
// public interface
return Preloader;
});
and this is the preloader QUnit test
'use strict';
define(function (require) {
var Preloader = require('Preloader');
var manifest = [
{ src : '../app/images/splash-screen.jpg', id : 'splash-screen' }
];
var assets = {};
var startFired = 0;
var updateFired = 0;
var completeFired = 0;
var totalLoaded = 0;
var scopetest = 'test';
var loaded = 0;
var pl = new Preloader({
manifest : manifest,
assets : assets,
onStart : function (e) {
startFired++;
},
onUpdate : function (e) {
updateFired++;
totalLoaded = e.loaded;
},
onComplete : function (e) {
completeFired++;
// adding the unit tests into the onComplete function fixed the inconsistent test results i was getting
test('Preloader tests', function () {
expect(4);
equal(startFired, 1, 'onStart was called once exactly');
ok((updateFired > 0), 'onUpdate was called at least once. Total: ' + updateFired);
equal(completeFired, 1, 'onComplete was called once exactly');
notEqual(pl.model.assets['splash-screen'], undefined, 'there was at least one asset loaded: ' + pl.model.assets['splash-screen']);
});
QUnit.start();
}
});
QUnit.stop();
});
Thankyou for your response and apologies for deleting the thread
This question already answered in the OP - this is my acceptance

jquery conflict with js script

welcome all ,
i have a problem with my images slider , it runs successfuly until poll script excuted then it stops , tried to combine both scripts didn't work also tried to use noConflict but in stops both of them .
this is the slider
(function ($) {
$.fn.s3Slider = function (vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderImage");
var itemsSpan = $("#sliderContent .sliderImage span");
items.each(function (i) {
$(items[i]).mouseover(function () {
mOver = true
});
$(items[i]).mouseout(function () {
mOver = false;
fadeElement(true)
})
});
var fadeElement = function (isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut / 2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if (items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut)
} else {
console.log("Poof..")
}
};
var makeSlider = function () {
current = (current != null) ? current : items[(items.length - 1)];
var currNo = jQuery.inArray(current, items) + 1;
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if (faderStat == true) {
if (!mOver) {
$(items[currNo]).fadeIn((timeOut / 6), function () {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
} else {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
}
})
}
} else {
if (!mOver) {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
} else {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
}
}
}
};
makeSlider()
}
})(jQuery);
and this is the poll script
window.onload = function() {
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
};
One potential problem could be the window.onload assignment. It is very prone to conflict.
Every time you do window.onload = the previous assignemnt will be overridden. See demo here:
The output shows that the first window.onload assignment never gets called, while the jQuery alternative does get called.
jQuery.noConflict does little in this regard. All it does is to prevent override the $ symbol so that another lib can use it.
So if you are also using the window.onload event to invoke the slider, then you have conflict. You can easily solve this problem by using the jquery format:
$(window).load(function() {
...
});
However usually you would tie the event to $(document).load(function(){...}); or in short form: $(function(){...}).
So for your poll that would be:
$(function(){
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
});
Hope that helps.
resolving conflicts in jquery (possibly with another JS library .. like script.aculo.us) can be resolved using noconflict()
http://api.jquery.com/jQuery.noConflict/
$.noConflict();
but make sure that u have no error in your javascript code itself. use firebug and
console.log('') to test your script.

Categories