Just going through the Novice to Ninja JS book, and at the end of ch2 the page behaves unexpectedly. The alert and prompt boxes pop up even though the HTML page hasn’t finished loading. I checked the code distributed with the book, and it does the same - which is different to the screenshot in the book. Anybody else got this issue? How do we get this fixed in vanilla JS?
I’m afraid I don’t have access to the book. Could you share the code for the page in question?
Is that the spoiler revealer code from the end of chapter 2 in the book?
Oh hang on, that’s the jQuery Novice to Ninja that I’m speaking of.
Time to investigate further.
The dojo svg image doesn’t have time to load, so the prompt and alert occurs before the image is shown on the screen.
The purpose of the exercise is to demonstrate how to use prompt and alert.
The pretty dojo background was added later, as earlier versions of the book don’t show the dojo image, as can be seen in this google version of end of chapter 2.
The lack of the dojo image on the first time that the page loads is good demonstration of why waiting for things to load can be beneficial, and why the blocking nature of prompts and alerts are detrimental.
It’s not fundamental to get that fully working though, as it’s irrelevant to the nature of the information that is being conveyed.
A simple way of fixing this though, is to wait for the window to finish loading before running the prompt and alert code.
window.addEventListener("load", function () {
const question = "What is Superman's real name?"
const answer = prompt(question);
alert(`You answered ${answer}`);
});
But, as said before, that introduces many things outside of the scope of what was being taught, such as the window object, event handlers, functions, and the loading process.
If it were me I would remove the dojo and page content instead, because problems with its display end up becoming more of a distraction than a benefit.
Thanks for the awesome response Paul! :)) I think I’m just too literal, so I see a picture and it doesn’t match what I’m doing, and I think something’s up. That is interesting though, that the image doesn’t load even though I assume putting the at the end of the body loads the markup.
Doing it your way would definitely focus on the function of the code. As a visual person, I like the graphics, but a heads up to expect the clunky functionality of the page would be good. Tends to stop me in my tracks until I know why it was done that way. There were a previously a number of “we’ll be taking a look at this later” notes when the reader is inevitably shown something beyond the scope.
All learning!
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.