动态加载外部CSS与JS文件
动态加载外部CSS与JS文件使用dom创建<script>或者<link>标签,并给他们附加属性,如type等。然后使用appendChild方法把标签绑定到另一个标签,一般是绑到<head>。 应用: 1、提高代码的复用,减少代码量; 2、添加一个javascript控制器和 session可以实现动态改变页面样式; 3、由于是页面是从上到下依次加载文件的,并且边加载边解释,所以可以添加javascript控制器控制页面文件的加载顺序,如先加载css布局文件,再显示有图片的css美化文件,之后再加载大的fals***件,或者安内容的重要性来加载。 To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "script" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together: document.getElementsByTagName("head")[0].appendChild(fileref) By referencing the HEAD element of the page first and then calling appendChild(), this means the newly created element is added to the very end of the HEAD tag. Furthermore, you should be aware that no existing element is harmed in the adding of the new element- that is to say, if you call loadjscssfile("myscript.js", "js") twice, you now end up with two new "script" elements both pointing to the same Javascript file. This is problematic only from an efficiency standpoint, as you''ll be adding redundant elements to the page and using unnecessary browser memory in the process. A simple way to prevent the same file from being added more than once is to keep track of the files added by loa |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |