Screenshot 2025-07-20 at 08-13-07 (3) Kolumbienforum - Antwort erstellen.png
@Steve
Thanks for the input – much appreciated! I initially went with plain JavaScript for simplicity and compatibility. Your suggestion adds a layer of robustness by wrapping the fetch call in a
try
block and delaying execution until
window.ready
, which could help in edge cases (e.g. if DOM elements aren't yet available).
Technically, fetch errors won't throw exceptions in the traditional sense – they return a resolved promise even for HTTP errors, so the
catch
block may not catch all network failures unless explicitly handled inside
.then()
or with
.catch()
chaining. That said, guarding the execution and avoiding any runtime error due to a missing element is certainly a plus.
I might update the snippet to include graceful failure handling using
.catch()
directly and a conditional DOM check, just to ensure it degrades cleanly when something goes wrong.
Thanks again – it’s great to refine these small tools with fellow enthusiasts!
Thanks again for the improvement suggestion — I’ve incorporated it into an updated version that adds better resilience while maintaining minimal complexity.
I opted to wrap the fetch logic in a try block inside $(window).ready() as you proposed, ensuring the DOM is fully loaded and avoiding potential issues with unresolved elements. The updated version also adds basic error tolerance without disrupting the user interface.
I haven’t tested it extensively yet, so feedback is welcome. One point to consider is that native fetch rarely throws in the usual sense — most failures (like network issues or unreachable endpoints) resolve normally unless .catch() is explicitly used. That said, guarding the whole block with try does help prevent runtime issues from other sources, such as missing DOM nodes or unexpected execution contexts.
Here’s the enhanced version as it stands:
Code: Select all
$(window).ready(() => {
try {
fetch('https://api.ipify.org?format=json')
.then(res => res.json())
.then(data => {
const display = document.getElementById('ip-display');
if (display && data?.ip) {
display.textContent = data.ip;
}
})
.catch(() => {
const display = document.getElementById('ip-display');
if (display) display.textContent = 'Unable to load IP';
});
} catch (err) {
// Silent fallback – avoids breaking the page
}
});
Appreciate any further refinement suggestions — great to evolve small utilities like this together.
You do not have the required permissions to view the files attached to this post.