Using AJAX to load an image in the background
Load image using javascript's fetch

Search for a command to run...
Load image using javascript's fetch

No comments yet. Be the first to comment.
Setting the content of an element with a number formatted with Indian currency

Defining a property to an object using Object.defineProperty()

Using PhotoSwipe v5 plugin and vanilla JavaScript with AlpineJS replacing jQuery for a photogallery section. Use of script type="module"

This is second part in the series to make use of getters and setters in an AlpineJS object, that converts INR to USD. Well, only a setter has been used here where a function call is made to the setter priceInINR when the textbox of the USD value chan...

Accessing a AlpineJS data in a vanilla JavaScript function out of the AlpineJS component
Alpine JS
15 posts
Content articles for AlpineJS (https://alpinejs.dev) - currently using alpinejs@3.15.11
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.