I have an electron app, it goes through a couple of files before creating the first window. But when it gets to the file that should create the window I checked and it is simply never ready. I am getting the error for creating a window before the app is ready but it's not a matter of time it really is just never ready.
I even put a while loop to while the app isn't ready and it never ends, I then moved it to the very first line of the first file (after requiring the app module) and it still got stuck and I have no idea why.
There really isn't any code to see here, it just the first line of the program there is nothing in the code that can affect it
The way you're checking the app readiness inside the loop isn't required at all. You can use the ready event as given in official docs or you can use the whenReady method which returns a promise to check the app is ready.
...
app.on('ready', () => {
...
...
});
//or
app.whenReady().then(() => {
...
});
Here is the example of using the whenReady.
Related
so i have a react website. I have a script file for animations/transitions called AppHomeScript.js that I import in the index.html with a script tag at the end:
<script src="./scripts/AppHomeScript.js" defer ></script>
the script file also has :
window.onload = () => {
console.log("LOADING SCRIPTS");
const homeButton = document.querySelector(".home-btn");
console.log("HOME BTN: ", homeButton);
const loginPage = document.querySelector(".login-page");
const loginButton = document.querySelector(".login-btn");
const registerButton = document.querySelector(".register-btn");
const registerPage = document.querySelector(".register-page")
const mainTexts = document.querySelector(".main-texts");
const hamburger = document.querySelector(".hamburger");
})
to make sure that it only runs after the components have finished loading. The problem is, in my local computer. the animations work fine in my chrome and operaGX browser. but it does not work on my
internet explorer,chrome's incognito mode, and my android phone's chrome. I also already hosted it in netlify, and I asked my friend if the animations work on their browser, but it does not. a part of the file console logs one of the documents it is trying to get, and it logs null. this gives me the idea that the script is being run even though the components haven't finished rendering.
I am using ES6 for the scripts, if you want to see the whole Script file, it is here:
https://github.com/BjornPython/locate-martial-arts-client/blob/main/public/scripts/AppHomeScript.js
here is the live demo of the app hosted in netlify:
https://poetic-capybara-66732c.netlify.app/
i tried different ways of importing the script file. like using useEffect and ComponentDidMount, or removing the
window.onload = () => {}
when i remove window.onload, the script runs before the components run, and it does not work on any of the browsers.
EDIT // EDIT // EDIT // EDIT // EDIT // EDIT // EDIT
I found a fix, but i'm not sure if this is the best way to deal with this problem.
I added a setTimeout function inside my window.onload.
window.onload = () => {
setTimeout(() => {
// MY CODE HERE // MY CODE HERE
}, 500);
}
If you have a better way of solving this problem, I would greatly appreciate it!
There are a few reasons why your JavaScript code may be running before your components have finished rendering in React:
Execution order: JavaScript code is executed in the order it is included in your HTML file. If your JavaScript code is included before your React components, it will execute before the components can render.
Asynchronous rendering: React components can be rendered asynchronously, which means that the component may not finish rendering before the JavaScript code runs. This can happen if your component makes an API call or performs other asynchronous operations.
State updates: React components can also update their state asynchronously, which means that changes to the state may not be reflected in the component before your JavaScript code runs.
To ensure that your JavaScript code runs after your React components have finished rendering, you can use the componentDidMount lifecycle method. This method is called after the component has finished rendering, so you can be sure that your component is ready before running any JavaScript code. Alternatively, you can use React's built-in useEffect hook to run code after the component has finished rendering.
I am using Headless JS in react native to create background service. My requirement is to create a service which will be invoked from MainActivity (For example on click of a button) and continue to execute even after the App goes to background. I could manage to create the service with Headless JS and invoke on button click. For simplicity I will explain with simple code
MyTask.js
module.exports = async () => {
console.log("I am called from java service");
for(var i=0; i<1000000;i++){
console.log("I am called from for loop"+i);
}
};
When using the above code, even after the app goes to background the for loop continues execution till i reaches 999999 also I am able to see the log message in console.
But my actual Task contains some async functions. For example when I use the following code in my task, it fails to print when the app goes to background
module.exports = async () => {
console.log("I am called from java service");
setInterval(() => {
console.log("I am called from java service inside setInterval");
}, 100);
};
The above code is supposed to print the log message continuously in 100 ms intervals. But the moment the app goes to background it stops printing. Again when the app resumes, it start printing again.
Can someone help on this?
My guess is that your activity is paused once your async headless task is over (from the caller perspective), this is what RN documentation suggests :
You can do anything in your task such as network requests, timers and
so on, as long as it doesn't touch UI. Once your task completes (i.e.
the promise is resolved), React Native will go into "paused" mode
(unless there are other tasks running, or there is a foreground app).
Although it's unclear, as you might think that JS timers - like setInterval would keep your code running... They won't.
The solution implied by RN doc is to implement a native service - for example a native timer instead of a JS one - which is basically what react-native-background-timer does...
EDIT
Regarding foreground execution, by default, headlessJS tasks are not allowed in foreground and will raise an error.
I wrote a module in node.js that performs some network operation. I wrote a small script that uses this module (the variable check below). It looks like this:
check(obj, function (err, results) {
// ...
console.log("Check completed");
});
Now here is the interesting thing. When this code executes as part of a mocha test, the test exits as expected. I see the log statement printed and the process exits.
When the code is executed as a standalone node script, the log statement gets printed, but the process just hangs.
When I try to debug it and I start the program using --debug-brk and use node-inspector, it exits early! I see that process.on 'exit' is called. It exits while some internal callbacks within the module weren't called yet. So the log statement above isn't printed either.
I am stuck now and am not sure why this is happening. Has anyone seen similar behaviour?
When you run it as a script and it hangs when "done", it means node still has callbacks registered waiting for events. Node doesn't know that those events won't fire anymore. You can either just call process.exit() if you know it's time to exit, or you can explicitly close/unbind/disconnect everything (network connections, db connections, etc). If you properly close everything, node should then exit.
The module wtfnode (mentioned by Nathan Arthur) or why-is-node-running can be really helpful tracking this down.
If the program exits unexpectedly, it can be because the event loop becomes empty and there is nothing else to do (because some code forgot to emit an error or do something else to keep the event loop going). In this case Node exits with code 0 and you won't get any error messages whatsoever, so it can be really confusing.
See https://github.com/archiverjs/node-archiver/issues/457 for an example of this happening.
I'm adding dynamic script by creating a script tag, setting its source and then adding the tag to the DOM. It works as expected, the script is getting downloaded and executes. However sometimes I would like to cancel script execution before it was downloaded. So I do it by removing the script tag from the DOM.
In IE9, Chrome and Safari it works as expected - after the script tag is removed from the DOM it doesn't execute.
However it doesn't work in Firefox - script executes even if I remove it from the DOM or change it its src to "" or anything else I tried, I cannot stop the execution of a script after it was added to the DOM. Any suggestions?
Thanks!
How about some sort of callback arrangement? Rather than have the dynamically added script simply execute itself when it loads, have it call a function within your main script which will decide whether to go ahead. You could have the main script's function simply return true or false (execute / don't execute), or it could accept a callback function as a parameter so that it can decide exactly when to start the dynamic script - that way if you had several dynamic scripts the main script could wait until they're all loaded and then execute them in a specific order.
In your main script JS:
function dynamicScriptLoaded(scriptId,callback) {
if (scriptId === something && someOtherCondition())
callback();
// or store the callback for later, put it on a timeout, do something
// to sequence it with other callbacks from other dynamic scripts,
// whatever...
}
In your dynamically added script:
function start() {
doMyThing();
doMyOtherThing();
}
if (window.dynamicScriptLoaded)
dynamicScriptLoaded("myIdOrName",start);
else
start();
The dynamic script checks to see if there is a dynamicScriptLoaded() function defined, expecting it to be in the main script (feel free to upgrade this to a more robust test, i.e., checking that dynamicScriptLoaded actually is a function). If it is defined it calls it, passing a callback function. If it isn't defined it assumes it is OK to go ahead and execute itself - or you can put whatever fallback functionality there that you like.
UPDATE: I changed the if test above since if(dynamicScriptLoaded) would give an error if the function didn't exist, whereas if(window.dynamicScriptLoaded) will work. Assuming the function is global - obviously this could be changed if using a namespacing scheme.
In the year since I originally posted this answer I've become aware that the yepnope.js loader allows you to load a script without executing it, so it should be able to handle the situation blankSlate mentioned in the comment below. yepnope.js is only 1.7kb.
I'd like to measure how long it takes to run the whole $().ready() scope in each of page.
For profiling specific functions I just set a new Date() variable at the beginning of the relevant part and then check how long it takes to get to the end of the relevant part.
The problem with measuring the whole $().ready scope is that it can sometimes run some of the code asynchronously and then I can not wait for it all to finish and see how long it has taken.
Is there any event which is fired once the page has completely finished running all $().ready code?
EDIT: Using Firebug or other client debuggers are not an option since I also need to collect this profiling information from website users for monitoring and graphing our web site's page load speeds
Thanks!
There will be no event fired because its virtually impossible for ready() to know when any asynchronous functions are done processing. Thus, you'll need to bake this functionality in yourself; you could use jQuery's custom events, or perhaps set a function to run on setInterval() that can introspect the environment and deduce whether or not everything else is done.
Swap out the jQuery ready function with a function that does your start and finish tracking, and calls the original method.
jQuery.ready = (function() {
var original = jQuery.ready;
return function() {
alert('starting profiler');
original();
alert('ending profiler');
};
})();
$(function() {
alert('this message will appear between the profiler messages above...');
});
Have you tried using Profiler in Firebug?