首页 > 代码库 > 异步加载脚本和样式

异步加载脚本和样式

<script>
        window.onload = function () {
            loadScriptURL(‘script/head.js‘)
            loadScriptcode(‘alert("hahaha");‘);
            loadStyleURL(‘a.css‘);
            var csscode = ‘#box{background:red}‘;
            loadStyleCODE(csscode);
        }
        function loadScriptURL(url) {
            var script = document.createElement("script");
            script.src = url;
            script.type = "text/javascript";
            document.getElementsByTagName(‘head‘)[0].appendChild(script);
        }
        function loadScriptcode(code) {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.text = code;
            document.getElementsByTagName(‘head‘)[0].appendChild(script);
        }

        function loadStyleURL(url) {
            var link = document.createElement(‘link‘);
            link.rel = ‘stylesheet‘;
            link.href = ‘text/css‘;
            link.href = url;
            document.getElementsByTagName(‘head‘)[0].appendChild(link);
        }

        function loadStyleCODE(code) {
            var style = document.createElement(‘style‘);
            style.type = ‘text/css‘;
           var box = document.createTextNode(code);// IE 低版本不支持
            style.appendChild(box);
            document.getElementsByTagName(‘head‘)[0].appendChild(style);
        }


    </script>


本文出自 “天空海阔” 博客,请务必保留此出处http://ether007.blog.51cto.com/8912105/1435065