Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load a specific css file in a specific case with JavaScript?

Tags:

javascript

I want to:

// Display loader spinner
// Check if ID or Class exist in HTML Page
// If ID or Class are found, load a specific css file
// Display HTML PAGE

Is it possible?

like image 399
Robeala Avatar asked Dec 25 '16 09:12

Robeala


People also ask

Can you change CSS file with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

How do I dynamically load CSS files?

Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.

Can you combine CSS and JavaScript?

Combining your JavaScript and CSS files is a useful method to reduce HTTP requests as well as latency if you are delivering them via the HTTP/1. x protocol. However, with the creation and vast adoption of HTTP/2, implementing this recommendation can actually harm the deliverability of your assets.


1 Answers

In JavaScript this how you check if a class exists in a page:

var isClassExist = document.getElementsByClassName('yourClass');
if (isClassExist .length > 0) {
    // elements with class "yourClass" exist
}

And this is how you append a css file to a page:

var cssId = 'myCss';  // you could encode the css path itself to generate id..
if (!document.getElementById(cssId))
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.id   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'http://website.com/css/stylesheet.css';
    link.media = 'all';
    head.appendChild(link);
}

The loader part:

You first have to include your spinner in the html:

<div id="dvReqSpinner" style="display: none;">
    <br />
    <center><img src="~/images/loading_spinner.gif" /></center>
    <br />
</div>

Then in JavaScript (using jQuery):

$("#dvReqSpinner").hide();
like image 117
user3378165 Avatar answered Sep 22 '22 06:09

user3378165