js动态加载css文件和js文件的方法

本文介绍了一种在网页中动态加载JavaScript和CSS文件的方法。通过创建新的`<script>`和`<link>`元素并将其添加到DOM中实现,同时利用`onreadystatechange`和`onload`事件来监测加载状态。
今天研究了下js动态加载js文件和css文件的方法。 网上发现一个动态加载的方法。摘抄下来,方便自己以后使用 [code lang="html"] <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Javascript includes - ready state and onload</title></pre> <script type="text/javascript"> var css; function include_css(css_file) { var html_doc = document.getElementsByTagName('head')[0]; css = document.createElement('link'); css.setAttribute('rel', 'stylesheet'); css.setAttribute('type', 'text/css'); css.setAttribute('href', css_file); html_doc.appendChild(css); // alert state change css.onreadystatechange = function () { if (css.readyState == 'complete') { alert('CSS onreadystatechange fired'); } } css.onload = function () { alert('CSS onload fired'); } return false; } var js; function include_js(file) { var html_doc = document.getElementsByTagName('head')[0]; js = document.createElement('script'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', file); html_doc.appendChild(js); js.onreadystatechange = function () { if (js.readyState == 'complete') { alert('JS onreadystate fired'); } } js.onload = function () { alert('JS onload fired'); } return false; } </script> </head> <body> <h1>javascript includes testing - testing readyState and onload</h1> This is a test file, part of the second follow up to the "<strong>javascript includes</strong>" article. <br /> To see the article, <a href="http://www.phpied.com/javascript-include">click here</a>. To see the follow-up article, <a href="http://www.phpied.com/javascript-include-ready">click here</a>. To see the second follow-up article, <a href="http://www.phpied.com/javascript-include-ready-onload">click here</a>. <p> </p> <ul> <li style="cursor: pointer" onclick="include_css('1.css')">Click to load 1.css</li> <li style="cursor: pointer" onclick="include_js('jsalert.js')">Click to load jsready.js</li> </ul> </body> </html> <pre> [/code]  

转载于:https://www.cnblogs.com/woaic/p/3942922.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值