Juneyoung Oh
Juneyoung Oh

Reputation: 7652

How to import css dynamically with js?

I got some condition, so I can not load some css, js in html. So I decide that pulling dynamically with $.get(). However, I tested js case, but do not have any clues in case of css.

Following is pulling and execute js from remote CDN dynamically.

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

Is it possible to get Other javascript file from remote?

<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, I can not use eval on css. What can I do? Is it even possible? Thanks so much!

P.S. If I pulling js like my example, can I use it globally after once I pulled this?

Upvotes: 0

Views: 296

Answers (1)

riccardolardi
riccardolardi

Reputation: 1750

You can insert a link element via jQuery, which points to your external css file like this:

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

Upvotes: 1

Related Questions