Skip to content

Load Style

Dynamically loading stylesheets into a page or incorporating styles using the <style> tag offers significant flexibility and performance enhancements for web development. This approach is particularly beneficial when you need to apply different styles based on user interactions or specific conditions within your application.

By dynamically injecting styles, you can ensure that your web pages remain lightweight upon initial load, therefore speeding up access times and improving the overall user experience. This method is especially useful for features that are not immediately visible or necessary, allowing for the progressive enhancement of the page as users engage with its content.

(async () => {
try {
await bstf.loadStyle({
url: 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css',
appendTo: 'head',
attributes: ["id=boostrap","data-test=2"],
});
console.log('Load boostrap on demand');
} catch (error) {
console.error(error);
}
})();

For times when you just need to add a bit of CSS, the inlineStyle feature makes it possible.

(async () => {
try {
await bstf.loadStyle({
inlineStyle: `h2 { background-color: coral; }`,
appendTo: 'head'
});
console.log('Inline Style applied successfully.');
} catch (error) {
console.error(error);
}
})();
  • url string The URL of the script to load.
  • inlineStyle: string The CSS styles to apply inline. If provided, the styles will be applied directly to the page within a <style> tag.
  • attributes: array An array of strings representing additional attributes to set on the script element. Each attribute can be in the form of “key=value” or just “key” for boolean attributes.
  • appendTo (string | Element) Optional. Specifies the element to which the script element will be appended. Can be a selector string (‘head’, ‘body’), or a DOM element reference. Defaults to ‘head’.