I am creating a webpage with multiple GeoGebra files embedded in it. That means I have, for each GeoGebra applet, a <div>
element in the <body>
with an associated script to configure it; and at the end of the <body>
I have the following script that adds all the applets to their associated <div>
s:
<script>
window.onload = function() {
applet_0.inject('ggb-element-0');
applet_1.inject('ggb-element-1');
applet_2_NoLimit.inject('ggb-element-2-NoLimit');
applet_2_YesLimit.inject('ggb-element-2-YesLimit');
applet_3.inject('ggb-element-3');
applet_4_Flat.inject('ggb-element-4-Flat');
applet_4_Faster.inject('ggb-element-4-Faster');
};
</script>
I noticed that if any of the first six lines of the script fails, for example if the associated file cannot be loaded, all lines following the failed line are not executed.
I want to make this work even if something goes wrong for one of the embeddings. I already discovered that I can’t have multiple window.onload
commands (only the last one is executed). Is there an alternative way to make this more fault-tolerant?
2
Answers
You could wrap each line with a
try {} catch {}
statement, but that would require a lot of copy-pasting and the code will be really messy. However, if you create a helper function, it would be possible without making the code unreadable:So usage is that you pass JavaScript code in string as argument to
runThroughErrors
function.Note that I chaged your
window.onload = …
to proper syntax for event that fires when page finishes loading.You can have multiple load event listeners by calling
window.addEventListener
instead of settingwindow.onload
. Listeners added in this way are executed in the order they are added. By providing{once: true}
as the third argument the event listener will be removed automatically after being called. The listeners can be added anywhere in code before the load event has been fired that you deem appropriate.For example the first two listeners could be added by