Javascript stops when loading from cache manifest in webapp - javascript

My javascript code stops when the side loads from the cache manifest in the Fullscreen WebApp Mode(iPad3/iOS6).
This has the consequence that you cant do anything in the first 5 seconds. After that you can use the site as normal.
1) Why does the JavaScript Code stop? (Event Problem?)
2) How can i fix it?
Involved is:
jquery-1.8.2.min.js
EDIT:
I have experimented and found out that the JavaScript code runs normally after the event onNoUpdate and onUpdateReady. Until these two events are initiated, it passes a large time. So this is not a option.
EDIT2:
`<script type="text/javascript">
$(document).bind('touchmove', false);
$(document).ready(function () {
applicationCache.onupdateready = function () {
if (confirm("Ihre Applikation wurde aktualisiert. Soll die Darstellung neu geladen werden?")) {
window.location.reload();
}
}
applicationCache.onnoupdate = function () {
}
var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
if (a[i].className.match("noeffect")) {
// Here happens nothing
}
else {
a[i].onclick = function () {
load();
window.location = this.getAttribute("href");
return false;
};
}
}
}
);`

Try inserting some logs in key spots to find out exactly where in the code the pause happens. Usually when you narrow it down enough, the answer becomes clear.

Related

vanilla JavaScript carousel: slides race after user views another tab then returns

I've built a little carousel programme in vanilla JavaScript and it's working great, except when I visit another browser window and then come back to my carousel window.
The slides race past each other, as though they've been waiting to run while I've been elsewhere, until it reaches the slide it would have been at had I been watching the whole time, which often slides in from the wrong side. Then it settles down and continues to work as expected. This behaviour is the same in Chrome and Firefox.
The full code is on GitHub at https://github.com/lucywho/lightweight-carousel but this is the relevant section of the script:
const slide = document.querySelectorAll("#carousel .carousel-slide");
const dots = document.querySelectorAll("#dots .dot");
const total = slide.length;
let last = total - 1;
let i = 0;
let timer;
let isTransitioning = false;
timer = setTimeout(moveSlide, 5000);
function moveSlide(index) {
isTransitioning = true;
if (typeof index == "number") {
if (i === index) {
return;
} else {
slide[i].classList.remove("onscreen");
dots[i].classList.remove("fill-in");
slide[i].classList.add("offscreen-left");
i = index;
dots[i].classList.add("fill-in");
slide[i].classList.add("onscreen");
}
} else if (i < last) {
slide[i].classList.remove("onscreen");
dots[i].classList.remove("fill-in");
slide[i].classList.add("offscreen-left");
i++;
dots[i].classList.add("fill-in");
slide[i].classList.add("onscreen");
} else if (i === last) {
slide[i].classList.remove("onscreen");
dots[i].classList.remove("fill-in");
slide[i].classList.add("offscreen-left");
i = 0;
dots[i].classList.add("fill-in");
slide[i].classList.add("onscreen");
}
timer = setTimeout(moveSlide, 7000);
}
document.addEventListener("transitionend", function(event) {
if (event.target.classList.contains("offscreen-left")) {
event.target.classList.remove("offscreen-left");
isTransitioning = false;
}
Am I right in thinking that the problem is something to do with the script continuing to run in the background even when the page is not displayed? And if so, how do I force JavaScript to pause? (I tried wrapping it all in a document.addEventListener("DOMContentLoaded", function(){} but that didn't help)
Many thanks in advance.
ETA: thanks to Andre, I've tried the following approach. Again, it runs happily when the page loads but I'm still getting a few seconds of weirdness when I return from another tab.
let screenVis = true;
if (screenVis) {
...
carousel code
...
}
document.addEventListener("visibilitychange", function() {
if (document.hidden === true) {
screenVis = false;
} else {
screenVis = true;
}
});
So, either I've mucked up my code (always possible) or something else is going on?

jQuery each not functioning correctly

I have a slider with 10 slider elements. However, only 7 out of 10 elements are rendered, given my data structure contains 20 sets. The site is hosted here
The code in question
function populateCarousell(cdata) {
var x = 0; //debug
jQuery(".wslide-slides .wslide-slide").each(function() {
var single = cdata.shift();
var jcurrSlide = jQuery(this);
jcurrSlide.find(".wslide-caption-text").text(single.title);
jcurrSlide.find("a").attr('href', "https://carousell.com/p/" +single.id);
jcurrSlide.css({'background-image':Base64.decode('dXJs')+'('+single.primary_photo_full_url+')'});
jcurrSlide.css({'background-image':'contain'});
jcurrSlide.css({'background-position':'50% 50%'});
jcurrSlide.css({'background-repeat': 'no-repeat'});
x++; //debug
jcurrSlide.find(".wslide-slide-inner2").removeAttr('style').find("img").css({'display':'none'});
});
alert(x); //Outputs 7
}
which is activated by (to ensure page fully loaded)
function caroDataCallback(data) {
if(document.readyState != "complete" ) {
setTimeout(function() { caroDataCallback(data); }, 2000);
}
else{
populateCarousell(data);
}
}
Upon examination in Chrome, the results is
That's because your page is not fully loaded when you call populateCarousell(cdata) function in your javascript file. Try instead of using $(document).ready(), use the $(document).load() to make sure all the images are loaded before you initiate your carousel.
Update: Use $(window).on('load', function() { .. }); instead.
Hope this helps.

javascript working in localhost but not when hosted?

I'm trying to implement a simple image slider on my website but it doesn't seem to want to work. Nothing happens at all. Nothing I can think of has worked thus far so I thought I'd ask here. This is my code.
window.onload = function(){
image = document.getElementById("slideShow");
index = 0;
setInterval(slide, 3000);
};
function slide(){
index++;
if(index >= 6) {index = 0;}
path = "images/Slideshow/image"+index+".jpeg";
image.setAttribute("src",path);
}
window.onload is pretty cheesy because nobody seems to agree on what onload actually means.
i would recommend you use
document.addEventListener("DOMContentLoaded", function(){
// code
});
Another thing u should be aware of is slow loading. If the scripts gets loaded after the ready event has been fired then your code will never trigger.
A solution is wrapping the ready function is a seperate module.
var eventReady;
(function(){
var funcArr = [];
eventReady = function(func){
funcArr.push(func);
}
document.addEventListener("DOMContentLoaded", function(){
for(var i=0;i<funcArr.length;i++){
try{
funcArr[i]();
}
catch(e){
throw(e);
}
finally{
continue;
}
};
eventReady = function(func){
func();
}
});
})();
and then use the module like:
eventReady(function(){
// code
})

Firefox, javascript and iFrame performance with Jquery

I'm having a bit of a jquery javascript performance issue, specifically related to Firefox.
We have a set of vimeo embeds, and the ids are pulled in via a json file. On each click, a new video is displayed. After the video is played, the container is removed and the title cloud is put back in. After a certain number of rounds, Firefox performance seriously degrades and you get the "unresponsive script" error. This isn't happening on any other browsers. Furthermore, the profiler in FF doesn't seem to point to a root cause of the slowdown.
I believe this is caused by poor iframe performance and how FF handles iframes, but I'm not entirely sure about this. Nothing else I'm doing is anything too, mostly just stock jquery functions like empty(), remove(), prepend(), etc.
I have implemented a click counter which will just refresh the page after a certain amount of click throughs. This resolved the problem, but it's a hacky solution which I seriously dislike. I would love some ideas on the root cause of this and any advice on how to solve it.
Here's the link to the site and the specific portion mentioned:
http://www.wongdoody.com/mangles
This isn't all the code, but this is the part that gets called every click.
Also, I have tried just swapping out the src="" in the iframe, but performance still degrades.
EDIT: I can confirm this is not a memory leak, I used about:memory and with addons disabled in safe mode I'm getting decent memory usage:
359.11 MB ── private
361.25 MB ── resident
725.54 MB ── vsize
Something in the vimeo embed is slowing down the javascript engine, but it's not a memory leak. Also, this is confirmed by the fact that I can resolve the issue by just refreshing the page. If it was a memory leak I would have to close FF altogether.
function getIframeContent(vid) {
mangle_vid_id = vid;
return '<div class="vimeoContainerflex"><div class="vimeoContainer"><iframe class="vimeo" style="z-index:1;" width="100%" height="100%" frameborder="0" allowfullscreen="" mozallowfullscreen="" webkitallowfullscreen="" src="//player.vimeo.com/video/' + mangle_vid_id + '?api=1&title=0&color=89ff18&byline=0&portrait=0&autoplay=1"></iframe></div></div>';
}
function show_titles() {
$('.mangle-btn').hide();
$('.vimeoContainerflex').remove();
$('span.mangle').hide();
if ($('#mangle-titles').length < 1) {
$('#wongdoody').prepend(wd_titles_content);
}
$('#arrow').show();
if (clicks > 12) {
location.reload();
}
$('#mangle-titles span').click(function() {
clicks = clicks + 1;
$('#mangle-wrapper').remove();
var vidID = $(this).attr('data-id');
if ($('.vimeoContainer').length < 1) {
if (vidID == "home") {
$('#wongdoody').prepend(getIframeContent(getRandom()));
} else {
$('#wongdoody').prepend(getIframeContent(vidID));
}
}
$('#arrow').hide();
vimeoAPI();
});
$('#mangle-titles span').not('noscale').each(function() {
var _this = $(this);
var classname = _this.attr('class');
var scaleNum = classname.substr(classname.length - 2);
var upscale = parseInt(scaleNum);
var addition = upscale + 5;
var string = addition.toString();
_this.hover(
function() {
_this.addClass('scale' + string);
},
function() {
_this.removeClass('scale' + string);
}
);
});
}
function vimeoAPI() {
var player = $('iframe');
var url = window.location.protocol + player.attr('src').split('?')[0];
var status = $('.status');
// Listen for messages from the player
if (window.addEventListener) {
window.addEventListener('message', onMessageReceived, false);
} else {
window.attachEvent('onmessage', onMessageReceived, false);
}
// Handle messages received from the player
function onMessageReceived(e) {
var data = JSON.parse(e.data);
switch (data.event) {
case 'ready':
onReady();
break;
case 'finish':
onFinish();
break;
}
}
// Helper function for sending a message to the player
function post(action, value) {
var data = {
method: action
};
if (value) {
data.value = value;
}
var message = JSON.stringify(data);
if (player[0].contentWindow != null) player[0].contentWindow.postMessage(data, url);
}
function onReady() {
post('addEventListener', 'finish');
}
function onFinish() {
setTimeout(show_titles, 500);
}
}
Part of you're problem may be the fact that you keep adding more and more click-handlers to the spans. After each movie ends the onFinish function calls show_titles again, which attaches a new (=additional) click-handler to the $('#mangle-titles span') spans. jQuery does not remove previously attached handlers.
Try splitting the show_titles function into two. init_titles should be called only once:
function init_titles() {
if ($('#mangle-titles').length < 1) {
$('#wongdoody').prepend(wd_titles_content);
}
$('#mangle-titles span').click(function() {
$('#mangle-wrapper').remove();
var vidID = $(this).attr('data-id');
if ($('.vimeoContainer').length < 1) {
if (vidID == "home") {
$('#wongdoody').prepend(getIframeContent(getRandom()));
} else {
$('#wongdoody').prepend(getIframeContent(vidID));
}
}
$('#arrow').hide();
vimeoAPI();
});
$('#mangle-titles span').not('noscale').each(function() {
var _this = $(this);
var classname = _this.attr('class');
var scaleNum = classname.substr(classname.length - 2);
var upscale = parseInt(scaleNum);
var addition = upscale + 5;
var string = addition.toString();
_this.hover(
function() {
_this.addClass('scale' + string);
},
function() {
_this.removeClass('scale' + string);
}
);
});
}
function show_titles() {
$('.mangle-btn').hide();
$('.vimeoContainerflex').remove();
$('span.mangle').hide();
$('#arrow').show();
}
I'd recommend trying to re-use the iframe instead of wiping and re-adding. Failing that, I think you may be out of luck. Your method of closing the iFrame is fine; your browser that it's running in is not.
You're overloading window with eventListeners. Each time a user clicks a video, you're attaching an event to window that fires every time you're receiving a message.
You can easily check this by adding console.log("Fire!"), for instance, at the beginning of onMessageReceived. You'll see that this function gets triggered an awful number of times after the user has performed some clicks on videos.
That surely has an impact on performance.
Hope this helps.

Using timers (onload)

Ok, firstly, I hardly know Javascript. I really don't know what I'm doing.
So, I have this code:
var interval_id = 0;
var prevent_bust = 0;
// Event handler to catch execution of the busting script.
window.onbeforeunload = function() { prevent_bust++ };
// Continuously monitor whether busting script has fired.
interval_id = setInterval(function() {
if (prevent_bust > 0) { // Yes: it has fired.
prevent_bust -= 2; // Avoid further action.
// Get a 'No Content' status which keeps us on the same page.
window.top.location = 'http://vadremix.com/204.php';
}
}, 1);
function clear ()
{
clearInterval(interval_id);
}
window.onload="setTimeout(clear (), 1000)";
After 1 second I want to clear the interval set earlier. This isn't working. How would I do what I'm trying to do?
If you substitute the last line with window.onload = function() { setTimeout(clear, 1000); }, it should do OK.
There are two errors in your code:
window.onload should be a function, rather than a string ("..."),
setTimeout accepts a function (clear), rather than the result from the function (clear())
By the way, these are some good places to learn JavaScript:
QuirksMode
Mozilla Developer Network

Categories

Resources