Using AJAX to load an image in the background

Using AJAX to load an image in the background

Load image using javascript's fetch

Ever tried loading an image using AJAX/fetch?

Here's a super simple example with AlpineJS parsing an IMG's src value as JavaScript. It can't get simpler than this.

<div x-data="{}">
    <img :src="await(await fetch('https://domain.com/myImage.jpg')).url" />
</div>

You'll have to add cors origin like the way it's done at bunny.net - https://share.getcloudapp.com/bLuARKwx

Here's a full source code :

<!DOCTYPE html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />    
    <title>Using AJAX to load an image in the background</title>
    <script src="https://unpkg.com/alpinejs@3.13.2/dist/cdn.min.js" defer></script>
</head>
<body>
    <div x-data="{}">
        <img :src="await(await fetch('https://anjanesh.b-cdn.net/island.jpg')).url" />
    </div>
</body>
</html>

Note the .url and the end of the closing await.

the .url is used to get the URL of the response obtained from the fetch operation, and it's accessed using await because fetch returns a promise.