Examples JavaScript ES modules Basic Example with HTML/CSS/JS
This contrived example demonstrates how to show a simple recommendation using the ESM version of the library. Instead of loading the library as a <script> tag, the import
statement is used.
index.html
Copy <!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<h4>Headless Recommendations</h4>
<p>Using ES modules</p>
<script type="module" src="index.js"></script>
</body>
index.css
Copy body {
font-family: Arial, Helvetica, sans-serif;
}
.item {
border: 1px solid #ccc;
padding: 0 10px;
margin: 5px;
width: 200px;
height: 300px;
display: inline-block;
vertical-align: top;
}
.item>a {
text-decoration: none;
}
.item>a>img {
width: 100%;
max-width: 200px;
}
index.js
Copy /* import module */
import { $fetchRecommendationData }
from 'https://cdn.obviyo.net/lib/obv-api.esm.js'
const SITE_ID = '{your siteId}'
/**
* Helper function to append a recommendation item
*/
function appendItem(item) {
const div = document.createElement('div')
div.className = 'item'
const html = `
<a href="${item.onlineStoreUrl}">
<h4>${item.title}</h4>
<img src=${item.featuredImage.originalSrc}>
</a>
`
div.innerHTML = html.trim()
document.body.appendChild(div)
}
/**
* Example function which calls for a recommendation
* In this case, most popular
*/
async function $showRecommendations() {
const result = await $fetchRecommendationData({
siteId: SITE_ID,
qualifiedName: 'psz-mpop'
})
const items = result.items
if (items && items.length) {
items.map(appendItem)
}
}
/**
* Simulate document ready
*/
function onDocumentReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback()
} else {
document.addEventListener("DOMContentLoaded", callback)
}
}
onDocumentReady(() => {
$showRecommendations()
})