JavaScript dynamically adds css styles and script tags

  • 2021-07-04 17:52:24
  • OfStack

[Dynamically Add css Styles]


<html>
        <head>
                  <script type="text/javascript">
                            window.onload=function(){
                                      var head=document.getElementsByTagName('head')[0];                       // Get to head Element 
                                      var link=document.createElement('link');                                                           // Create link Element node, which is link Label 
                                                link.rel="stylesheet";                                                                                                  // For link Tag addition rel Attribute 
                                                link.href="basic.css";                                                                                                  // For link Tag addition href Attribute   ,   The property value is css Path of outer chain style sheet 
                                      head.appendChild(link);                                                                                                  // Will link Element node is added to the head Element child node 
                                      
   }
                  </script>
        </head>
        <body>
                  <div id="div1"> Test </div>
        </body>
</html>

[Dynamic Add script Tag]

Same principle as above


<html>
    <head>
          <script type="text/javascript">
                   window.onload=function(){
                      var head=document.getElementsByTagName('head')[0];             // Get to head Element 
                      var script=document.createElement('script');                             // Create script Label 
                            script.type="text/javascript";                                            // For script Tag addition type Attribute 
                            script.src="basic.js";                                                        // For script Tag addition scr Property with the value of js Path 
                      head.appendChild('script');                                                  // Will script Tag is added to the head Under the child nodes of 
}
          </script>
    </head>
    <body>
          <div id="div1"> Test </div>
    </body>
</html>

Related articles: