What is the best method for dynamically loading CSS using JavaScript?

Due to a certain condition I have, I am unable to load some CSS and JS in my HTML. As a solution, I've decided to dynamically pull them using $.get(). While I have successfully tested pulling and executing js remotely, I am facing some challenges when it comes to css.

Below is an example of pulling and executing js from a remote CDN:

Pulling and Executing https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js'>

Is it possible to fetch other javascript files remotely?

<pre>
    <code class='java'>
        System.out.println("It's done!");
    </code>
</pre>

<script>
    const highlightCDN = 'http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/highlight.min.js';
    $(function(){
        $.get(highlightCDN, function(data){
            console.log('done!');
            eval(data);
        }).done(function(){
            $('pre code').each(function(i, block){
                console.log(i);
                hljs.highlightBlock(block);
            });
        });
    });
</script>

However, using eval on css is not an option. I am unsure of what to do next. Is there a workaround for this issue? Your help would be greatly appreciated!

P.S. If I pull js as shown in my example, can I utilize it globally after its initial pull?

Answer №1

If you want to add a link element through jQuery that leads to an external CSS file, you can achieve it by following this code snippet:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'put-your-external-css-stylesheet-url-here'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

forward to a different link following the backend script execution

I am facing a challenge with the signup.php page which includes a Facebook login button. The structure of the page is as follows: <?php if(!isset($_SESSION['logged_in'])) { echo '<div id="results">'; echo '<!-- ...

What is the best way to utilize XMLHttpRequest for sending POST requests to multiple pages simultaneously?

I have a unique challenge where I need to send data to multiple PHP pages on different servers simultaneously. My logic for sending the post is ready, but now it needs to be executed across various server destinations. var bInfo = JSON.stringify(busines ...

Display a single div and conceal the rest upon clicking a link

Trying to find a way to hide all other divs when clicking on a navbar link to toggle them. Currently, the divs stay active when a new link is clicked. The goal is for them to slide up and the clicked one to slide down. <script type="text/javascript> ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Setting filters programmatically in Mui X Data Grid

I am currently working with the MUI Data Grid (pro version) and I am looking to implement checkboxes in the sidebar to filter different columns. Consider three columns: * Column Letters: ['a', 'b', 'c', 'd', etc.] * ...

Error: Module not found - The package path "." is not exported from the specified package. As a result, Firebase will not update in your Next.js

I have been developing a Next.js application that retrieves data from a Firebase collection. During the process of connecting to the Firebase database, I have come across the following error: Failed to compile. Module not found This error seems to be ori ...

Use a CSS rule only if the element is not nested by using the :not selector

Could use some assistance with this coding issue: .element { border: 1px solid red; display: block; } I want to exclude this rule when .element is a descendant of .no-border using the :not pseudo-selector. For example: <div class="element">I ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

Preventing text from wrapping around an image: tips and tricks

I've been struggling to prevent text from wrapping around an image on my webpage. Despite various attempts like enclosing the image and text in separate <div> elements, setting both the <img> and <div> to display as block, and even t ...

Error: The function $(...) does not contain a progressbar

I encountered a TypeError saying $(...).progressbar is not a function when loading the Gentelella - Bootstrap Admin Template Page. This error is affecting many jQuery processes. How can I resolve this? Error in my Code: (custom.js) // Progressbar if ($( ...

Issue with displaying list items in Ajax Accordion with CSS

I have implemented an accordion control extender on my webpage, and it is functioning properly. I added a CSS file to display it as a list, which is working perfectly in all browsers except for IE compatibility view. In IE compatibility view, the list-styl ...

When using `defineModel` in Vue, the returned value can be either an object or

defineModel() is a new feature introduced in Vue 3.4+. The official documentation provides the following example: const model = defineModel() model.value = 'hello' Initially, it appears that model is an object with a value property. However, th ...

Implement the Show/Hide TinyMCE Functionality in your <textarea></textarea> Box

Information I recently added TinyMCE to my website after discovering that a website I frequently visit uses it. While their design and functionality are different, I managed to replicate their look on my own site and now want to implement a specific featu ...

Angular Automatically Generated Identifier for Event Detection

By using jQuery, I can easily target an ID that starts with "conditionValue" $(document).on('focus', "[id^=conditionValue]", function (event) { // code }); But how can I achieve the same in Angular when looking for an ID starting with somet ...

node.js issue with chalk package

**When I want to use the chalk package in node.js, I encounter the following issue:** index.js const chalk = require('chalk'); console.log(chalk.bgRed.inverse("hello world")); console.log(chalk.blue.inverse('Hello') + &ap ...

Adjust the background color of children based on the parent's mouseover event

Seeking a solution to fill three bars with varying percentages: <div class="bars" style="width:0%; background-color: red;"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </ ...

Integrate CSS and JavaScript files into Node Express

I am facing an issue including my CSS file and JavaScript file in a node-express application, as I keep getting a 404 not found error. Here is the code snippet that I am using: 1. In server.js var http = require('http'); var app = require(' ...

The interface 'IProduct' does not include several properties found in type 'IProduct[]', such as length, pop, push, concat, and many more

My goal is to transfer data between parent and child components using React and TypeScript. I have defined the following interfaces: export interface IProduct { id: string; name: string; price: string; image: string; ...

Attempting to modify the chosen indicator symbol in a multiselect dropdown using bootstrap-select

The current icon that I'm considering changing Perhaps to something similar in the same library but different Currently working on a multi-select dropdown using bootstrap-select and struggling with the checkmark design, although it is important to i ...

Enabling communication between my React frontend and Express server

I currently have a Digital Ocean Ubuntu VPS set up with Apache, Node, and Mongo running. I can successfully retrieve data from my database using CURL on the server and my node backend is running on port 3000. For my React frontend, I am using Fetch and it ...