Is there any way to load css and javascript from a string?

后端 未结 3 977
我寻月下人不归
我寻月下人不归 2021-01-06 10:30

I\'ve seen many examples of loading CSS and javascript dynamically from a file. Here\'s a good example. But is there a way to load CSS or javascript as a string? For exam

相关标签:
3条回答
  • 2021-01-06 11:05
    var javascript = "alert('hello');";
    eval(javascript);
    

    This will load the JavaScript from a string, but be warned that this is highly insecure and not recommended. If a malicious process ever interfered with your string of JavaScript, it could result in security issues.

    As far as CSS goes, you can append a style tag to the page using jQuery, like so:

    $('head').append("<style>body { background-color: grey; }</style>");
    

    Or, for the JavaScript purists:

    var s = document.createElement("style");
    s.innerHTML = "body { background-color:white !important; }";
    document.getElementsByTagName("head")[0].appendChild(s);
    
    0 讨论(0)
  • 2021-01-06 11:14

    but, this code work on only single HTML file that contain style tag

    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style></style>
    </head>
    <body>
        <div class="foo"></div>
        <div class="bar"></div>
    </body>
    <script>
        const cssText = `.foo{
                background-color: black;
                width: 100px;
                height: 100px;
            }
            .bar{
                background-color: gray;
                width: 100px;
                height: 100px;
            }`
        document.querySelector("style").innerText = cssText;
    </script>
    </html>```
    
    0 讨论(0)
  • 2021-01-06 11:25

    Another way without using potentially dangerous eval and innerHTML is creating a link element with base64 encoded URL:

    function loadCSS(cssStyles) {
      const link = document.createElement('link');
      link.href = `data:text/css;base64,${btoa(cssStyles)}`;
      link.type = 'text/css';
      link.rel = 'stylesheet';
      document.getElementsByTagName('head')[0].appendChild(link);
    }
    
    0 讨论(0)
提交回复
热议问题