动态加载CSS和JS文件方法
今天在做一个小工具的时候遇到一个动态加载js文件的问题。
后台会不定时的修改一个js文件,文件里面存的是一个数组,那么当页面在执行某个操作的时候需要重新获取该js文件的内容,但是页面又不能进行刷新操作。
试用了网上的2种方法,均无法实现需要的效果
方法1:
<script language=Javascript src='a.js' charset=gb2312 id="Js"> </script>
document.getElementById('Js').src=document.getElementById('Js').src
方法2:
document.write(“<script language=Javascript src='a.js' charset=gb2312 id="Js"> </script> ”);
故而问以前同学
得到秘籍一份,特此转载
一下内容转载于:
追梦青年-专注C#与.NET
http://www.woaic.com/2013/09/663
<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>

浙公网安备 33010602011771号