Using AJAX to load an image in the background

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.

0
Subscribe to my newsletter

Read articles from Anjanesh Lekshminarayanan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anjanesh Lekshminarayanan
Anjanesh Lekshminarayanan

I am a web developer from Navi Mumbai working as a consultant for cloudxchange.io. Mainly dealt with LAMP stack, now into Django and trying to learn Laravel and Google Cloud. TensorFlow in the near future. Founder of nerul.in