iT邦幫忙

1

動態載入CSS/JS

動態載入CSS

準備style.css

p {
    color: green;
    text-align: center;
} 

準備HTML


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <script>
        function dynamicLoadCss(url) {
            var head = document.getElementsByTagName('head')[0];
            var mycss = document.createElement('link');
            mycss.type = 'text/css';
            mycss.rel = 'stylesheet';
            mycss.href = url;
            head.appendChild(mycss);
        }
        if (1 == 1) {
            dynamicLoadCss("style.css");
        }
    </script>

    <p>This is a paragraph.</p>
</body>
</html>

動態載入JS

準備myscript.js
alert("hi,everybody");

準備HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <script> 
        function dynamicLoadJS(url) {
            var head = document.getElementsByTagName('head')[0];
            var myscript = document.createElement("script");
            myscript.type = "text/javascript";
            myscript.src = url;
            head.appendChild(myscript);
        } 
        if (1 == 1) {
            dynamicLoadJS("myscript.js");
        }  
    </script>

    <p>This is a paragraph.</p>
</body>
</html>

ref
http://www.victsao.com/blog/81-javascript/135-javascript-linkcss
https://tw.saowen.com/a/02517a131abc7dcd06edb4563dcafe0debc1b636d414143dad895cfc0831552e


尚未有邦友留言

立即登入留言