2

I'm new to Electron (just like to English :).
I'm trying to output a simple alert after loading and rendering the contents of the main window.

index.html:

<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="styles.css">
    <title>Test</title>
  </head>
  <body>
    ...
    Here's some content and images. A lot of them.
    ...
    <script src="alert.js"></script>
  </body>  
</html>

alert.js:

//Simple alert with some system information
alert("!@#$%^&*");

But an alert appears before the contents of the window are drawn. Defer and async don't help (i.e. <script defer async src="alert.js"></script>). What am I doing wrong? It seems to me that this is a very simple and stupid question, but I can not find an answer.

UPD: The only way I found for now is to use setTimeout:

setTimeout(function(){
     alert("!@#$%^&*");
}, 300);
Artik
  • 155
  • 4
  • I think script runs just after your body content is fetched and sent to parse, to run alert.js after content rendering, in jquery, you should try `$(window).on('load', function(){ alert("sdfsd"); })` – Rahul Jain Oct 17 '17 at 05:29
  • Possible duplicate of [Javascript alert loads before page displays](https://stackoverflow.com/questions/12280575/javascript-alert-loads-before-page-displays) – AZinkey Oct 17 '17 at 05:32
  • @Rahul Jain. I have not yet become acquainted with jquery. Where do I insert this code? – Artik Oct 17 '17 at 05:36
  • You don't need jQuery: `window.addEventListener("load",x=>alert("hello world")) ` – HMR Oct 17 '17 at 05:39
  • @HMR. This code shows alert defore rendering contents of the window too. – Artik Oct 17 '17 at 05:41
  • @Artik, yea, but could you tell me why this approach isn't working? It is intended to do this, no? – Rahul Jain Oct 17 '17 at 05:51
  • @Rahul Jain. I wish I knew! But I've tried all the options I have found! Only the version with setTimeout works. – Artik Oct 17 '17 at 05:55
  • https://stackoverflow.com/questions/8611713/running-javascript-after-page-is-fully-rendered – Rahul Jain Oct 17 '17 at 05:59
  • @Rahul Jain. It is about setTimeout too. I'm curious, is this the only way? – Artik Oct 17 '17 at 06:09
  • A more natural "electron-way" of doing it would be adding a `'dom-ready'` event listener to your browserwindow in **main** process and pop up custom alert window from there. No need to hack these things in renderer process at all costs – pergy Oct 18 '17 at 08:42
  • Also, `window.onload = () => { alert('resource has loaded') }` should work here – pergy Oct 18 '17 at 08:58

1 Answers1

2

Since your code is at the bottom of the page you can us an IIFE (Immediately Invoking Function Expression):

(function() {
alert("!@#$%^&*");
}());

You can also use a setTimeout:

(function() {
    setTimeout(function () { 
        alert("!@#$%^&*"); 
    } , 2000)
}());