Using jQuery the following would log that the app had loaded once the DOM and all assets had been downloaded by the browser:
$(window).load(function() {
console.log('app loaded');
});
However I don't want this check to happen until after some other things have run.
So for example:
function checkLoaded()
{
$(window).load(function() {
console.log('app loaded');
});
}
So let's say I call this function after a bunch of other functions.
The problem is, because $(window).load(function() is an event listener, when I call the checkLoaded() function the event won't ALWAYS run (because it MAY have already been fired because everything has downloaded BEFORE the checkLoaded() function has run).
Any ideas on how I can do this?
I tried this:
function checkLoaded()
{
if(loaded)
{
console.log('app loaded');
}
else
{
checkLoaded(); // keep checking until the loaded becomes true
}
}
$(window).load(function(){
loaded = true;
});
But the problem here is that the checkLoaded function COULD get called hundreds of times in a few seconds and isn't a nice way of handling this.
UPDATE: The function is called using checkLoaded(); Just so everyone knows I am calling the function!
UPDATE 2:
The plan is essentially this:
function init() {
start();
}();
function start() {
// Show Preloader... and other stuff
/// Once all logic has finished call checkLoaded
checkLoaded();
}
function checkLoaded() {
if(loaded) {
show();
}
}
function show() {
... // show app
}
So I should be able to know if the status of loaded is true, but keep checking until it becomes true as it may be true or false when I get to the checking stage.
You run it either on window load or if it's already done using such kind of code:
function onLoad(loading, loaded) {
if (document.readyState === 'complete') {
return loaded();
}
loading();
if (window.addEventListener) {
window.addEventListener('load', loaded, false);
} else if (window.attachEvent) {
window.attachEvent('onload', loaded);
}
}
onLoad(function() {
console.log('I am waiting for the page to be loaded');
}, function() {
console.log('The page is loaded');
});
var loaded=false;
$(window).load(function() {
loaded=true;
});
function checkLoaded()
{
// do something if loaded===true
}
Try this
function checkLoaded()
{
$(window).load(function() {
console.log('app loaded');
});
}
checkLoaded();
you want to make checkLoaded block and thats a bad idea:
javascript has no threads and blocking like that will just burn CPU while potentially blocking the whole script.
don't wait like you do for loaded to be to true. use the eventhandler as it is meant to be used.
maybe give checkLoaded a parameter to a function you want called:
function checkLoaded(continueWhenLoaded) {
$(window).load(function() {
continueWhenLoaded();
});
}
Have you looked into a solution involving jQuery's .promise() and .done()? Look at some of the examples in the documentation, it might be what you are looking for.
Related
In my Rails 5.2.2 app I am using Turbolinks.
I have discovered that when I leave a page, the functions that were started continues.
I have organised my functions below a return statement that checks the body class. In my example below, if the body class is not foobar the functions below do not run.
// assets/javascripts/pages/foobar.js
var goLoop;
$(document).on("turbolinks:load", function() {
if (!$("body").hasClass("foobar")) {
return;
}
return goLoop();
});
goLoop = function() {
return setTimeout((function() {
console.log("Hello");
return goLoop();
}), 1000);
};
First time I visit the page, the goLoop function is triggered.
When I follow a link away from the page, the function runs. If I had not used Turbolinks, this would not have happened.
If I follow another link back to the page, the function is triggered again, so now it runs twice.
How can I avoid this, without disabling Turbolinks?
Use the turbolinks:before-cache to teardown your timeout using clearTimeout. You will need to keep a reference of the current timeout ID. So your solution might look like:
var goLoop;
var timeout;
$(document).on("turbolinks:load", function() {
if (!$("body").hasClass("foobar")) {
return;
}
return goLoop();
});
goLoop = function() {
return timeout = setTimeout((function() {
console.log("Hello");
return goLoop();
}), 1000);
};
$(document).on("turbolinks:before-render", function() {
clearTimeout(timeout);
});
You can use PageVisibilityAPI to see is current page active or not.
and for the loop issue, you should check whether it's exist or not then run timeout function.
I really can't figure out how to do it. I need to call somefunc() from file.js file on page load.
My file.js contains:
function somefunc() {
pc.somefunc(gotLocalDescription,
function(error) {
console.log(error)
}, {
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
});
}
// Socket.io
var socket = io.connect('', {
port: 1234
});
function sendCall(call) {
socket.emit('call', call);
}
socket.on('call', function(call) {
if (call.type === 'offer') {
pc.setRemoteDescription(new SessionDescription(call));
createAnswer();
} else if (call.type === 'answer') {
console.log('10--if call type is answer');
pc.setRemoteDescription(new SessionDescription(call));
} else if (call.type === 'candidate') {
var candidate = new IceCandidate({
sdpMLineIndex: call.label,
candidate: call.candidate
});
pc.addIceCandidate(candidate);
}
});
consider using
Trigger
instead
You can simple call the function which is in another file.
Have created a plunker.Also note it has a seperate file file.js. If you using name spacing please take care of that.
Click Me
WORKING COPY
You can use this:
click
But first you must include file.js in you html
<script type="text/javascript" src="file.js">
Using window.onload (pure javascript), you can call your somefunc() of file.js on page load, as following:
function somefunc() {
alert('somefunc() of file.js called!');
/*
* Your logic goes here.
*/
}
window.onload = somefunc();
DEMO
While, if you want to use jQuery, then include jquery source first and then your custom script file containing your method and DOM ready call, as following:
function somefunc() {
alert('somefunc() of file.js called!');
/*
* Your logic goes here.
*/
}
jQuery(document).ready(function(){
somefunc();
});
// OR
jQuery(function({
somefunc();
});
First make sure you have included your file.js to head of your html and the location to file is correct.
I am using a function first which adds a class that causes the page to fade to 0 on clicking an anchor tag. How would I add the following...
if style = opacity "0" (in other words function one has successfully completed) add the next function. The code is given below.
They both run independently from there respective triggers but not sure how to ensure that function two runs only on completion of the first.
document.getElementsByTagName("a")[1].addEventListener("click", first);
function first() {
"use strict";
document.getElementById("content").classList.add("animation")
}
function next() {
"use strict";
document.getElementById("profile").classList.add("animation");
}
document.getElementsByTagName("a")[1].addEventListener("click", function(){
document.getElementById("content").add('animation');
next();
});
function next(){
if (document.getElementById("content").contains('animation')) {
document.getElementById("profile").classList.add('animation');
} else {
return false;
}
}
I recommend you to use JQuery, it is much more easier to manipulate css attributes and stuffs. And for pure javascript, I think it was already answered here, it might not be straight answer, but it might help you out.
Use callback functions
function func(value, callback){
//do stuff
callback();
}
In your case
function first(alphavalue, second) {
// do some stuffs
if(alphavalue == 0) {
// run the call back
second();
}else { // do no stuffs }
}
Hope it helps!!
$("#content").on("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",
function(event) {
// Do something when the transition ends
next();
});
Check transition end event handling and this.
Why would my jquery/javascript be buggy?
(using foundation 4.3.2 with Jquery 1.10.2)
Firefox always gives a message to stop the script:
"A script on this page may be busy, or it may have stopped responding..."
Here is the function that gives the problems
function preparePlz() {
$('#plzform').on("submit", function (event) {
event.preventDefault();
var plzVal = $('#plz').val();
var regex = new RegExp("^([0-9]{5})$");
if (!regex.test(plzVal)) {
$('.errormessage').addClass("error");
if ($('.errormessage').hasClass("hide")) {
$('.errormessage').removeClass("hide");
}
$("#plz ").addClass("error");
}
else if(regex.test(plzVal)) {
$('.errormessage').addClass("hide");
$('.errormessage').removeClass("error");
$('#plz').removeClass("error");
$('#message').removeClass("hide");
var plzZone = plzVal.substring(0, 2);
$('#plzModal').foundation('reveal', 'open', {
url: 'http://vaeplan.com/kontact/zone',
data: {showtemplate: false, r: plzZone}
});
}
});
preparePlz();
}
$(document).ready(function () {
preparePlz();
});
You have infinite recursion. Think about it, what happens on document ready? preparePlz is called. What happens inside preparePlz? preparePlz is called. What happens inside preparePlz? preparePlz is called.
The last thing function preparePlz does is run itself:
preparePlz();
When the page loads preparePlz is run once, then goes into an infinite loop.
Change
});
preparePlz();
}
to
});
}
It seems that helloworld.js gets loaded multiple times based on the number of times I click #load. I say this because when I look at Google Chromes Developer Tools Network tab, it shows helloworld.js as many times as I click #load.
$(document).ready(function() {
$("#load").click(function(){
$.getScript('helloworld.js', function() {
hello();
});
});
});
The hello() function looks like this:
function hello(){
alert("hello");
}
Is it possible to detect if helloworld.js has already loaded?
So if it hasn't loaded, load it, and if it has loaded, don't load it.
This is what Developer Tools currently shows me if I click the #load button 4 times:
Set a flag when file loaded successfully. If flag is set then skip the file loading again.
Try this code,
var isLoaded = 0; //Set the flag OFF
$(document).ready(function() {
$("#load").click(function(){
if(isLoaded){ //If flag is ON then return false
alert("File already loaded");
return false;
}
$.getScript('helloworld.js', function() {
isLoaded = 1; //Turn ON the flag
hello();
});
});
});
So why not only fire the event once like this:
$("#load").one("click", function() {
$load = $(this);
$.getScript('helloworld.js', function() {
hello();
// bind hello to the click event of load for subsequent calls
$load.on('click', hello);
});
});
That would prevent subsequent loads and avoids the use of a global
Another option is letting .getScript() run but let it take the script from browser's cache so you won't have it reloaded each and every time.
To achieve this, add such code:
$.ajaxSetup({
cache: true
});
This is taken from the documentation page.
You could create a helper function:
var getScript = (function() {
var loadedFiles = {};
return function(filename, callback) {
if(loadedFiles[filename]) {
callback();
} else {
$.getScript(filename, function() {
loadedFiles[filename] = true;
callback();
});
}
};
})();