Advanced Techniques for Including JavaScript and CSS Files in Sitecore Content Hub


Just as a chef needs to add different ingredients to create a delicious dish, as a developer, you may need to include custom JavaScript and CSS files in your Sitecore Content Hub implementation. These files may contain functions, styles, or other code that you want to use across multiple pages or components.

In this article, we'll show you how to include these essential ingredients in your Sitecore Content Hub dishes and determine the position to inject them in the page header. This approach will help you keep your recipe organized, reduce duplication, and make it easier to maintain your custom code.

Step 1: Upload your files as assets

The first step is to upload your custom JavaScript and CSS files as assets in Sitecore Content Hub. You can do this by navigating to the Digital Asset Management section of your Content Hub instance and creating a new asset. Upload your JavaScript or CSS file, add any metadata or tags as needed, and save the asset.

Make a note of the asset ID for each file. You'll use this ID to fetch the asset and include it in your pages.

Step 2: Include your files in your pages

To include your JavaScript and CSS files in your pages, you'll need to use the getAsset function. This function fetches the asset by its ID, creates a new script or link element with the appropriate attributes, and inserts the element into the page header.

Here's an example of how to include a JavaScript file in your page:

const jsAssetId = "976160"; // replace with your asset ID
const position = 1; // replace with the desired position in the header, or remove for default position

$(document).ready(function() {
if (!jsAssetId || jsAssetId.length === 0) {
return;
}
getAsset(`/api/entities/${jsAssetId}`, 'downloadOriginal',position, type);
});


This example fetches the asset by its ID using the getAsset function, creates a new script element with the src attribute set to the asset URL, and inserts the element into the page header. The position parameter specifies the position to insert the element, or leave it undefined for the default position at the end of the header.

Here's an example of how to include a CSS file in your page:

const cssAssetId = "976169"; // replace with your asset ID
const position = 1; // replace with the desired position in the header, or remove for default position

$(document).ready(function() {
if (!cssAssetId || cssAssetId.length === 0) {
return;
}
getAsset(`/api/entities/${cssAssetId}`, 'downloadOriginal',position, type);
});

getAsset function

We have extended the getAsset function described in this blog post read blog post to handle the injection of JavaScript and CSS files. 


window.getAsset = async function getAsset(endpoint, rendition, position, type) {
try {
const response = await $.ajax({
url: endpoint,
method: 'GET',
});
let href = null;
if (response[rendition] && response[rendition][0] && response[rendition][0].href) {
href = response[rendition][0].href;
} else if (response.renditions && response.renditions[rendition] && response.renditions[rendition][0] && response.renditions[rendition][0].href) {
href = response.renditions[rendition][0].href;
} else if (response.original && response.original[0] && response.original[0].href && !type) {
// Use the default rendition if the requested rendition is not found and the type is not specified
href = response.original[0].href;
}
console.log("Include: " + href);
if (href && type) {
let asset = null;
if (type === "css") {
asset = document.createElement("link");
asset.rel = "stylesheet";
asset.href = href;
} else if (type === "js") {
asset = document.createElement("script");
asset.src = href;
}
const head = document.getElementsByTagName("head")[0];

if (position !== undefined) {
const existingElement = head.children[position];
head.insertBefore(asset, existingElement);
} else {
head.appendChild(asset);
}
}
return href;
} catch (error) {
console.error(`An error occurred while fetching the asset from '${endpoint}': ${error}`);
return null;
}
}

window.getAsset is a way of defining a function that is accessible from anywhere in your code, regardless of the scope in which it was defined.

In JavaScript, the global window object is always present in the browser environment and provides a way to define properties and functions that are accessible throughout your code. By defining getAsset as a property of the window object (window.getAsset), you are essentially making it a global function that can be called from anywhere in your code, even if it's defined within a smaller, more contained scope.

Using window.getAsset can be useful in situations where you need to define a function that needs to be accessed from multiple places in your codebase or across different files. It can also help to make your code more modular and easier to maintain, as it allows you to keep related functions and variables grouped together in logical, self-contained units.

Conclusion

By following this approach, you can include custom JavaScript and CSS files in your Sitecore Content Hub implementation and determine the position to insert them in the page header. This can help you keep your code organized, reduce duplication, and make it easier to maintain your custom code.

Make sure to upload your files as assets in the Digital Asset Management section of your Content Hub instance and make a note of the asset IDs. Then, use the getAsset function to fetch and include the assets in your pages. You can specify the position to insert the elements in the header, or leave it undefined for the default position at the end of the header.

We hope this article helps you include custom JavaScript and CSS files in your Sitecore Content Hub implementation. Let us know if you have any questions or feedback.

Comments