三种动态加载js的jquery代码,jquery动态加载文件很方便,只需这样:$.getScript("test.js");即可。
来看完整的例子:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=gb2312" /> <title>jquery 动态加载js的三种方法 - www.jbue.com</title> //方法一 <script language="网页特效"> $.getscript("test.js"); //方法二 function loadjs(file){ var head = $('head').remove('#loadscript'); $("<scri"+"pt>"+"</scr"+"ipt>").attr({src:file,type:'text/javascript',id:'load'}).appendto(head); } //可以一行代码全部搞定: //方法三 $("<scri"+"pt>"+"</scr"+"ipt>").attr({src:file,type:'text/javascript',id:'load'}).appendto($('head').remove('#loadscript')); </script>
例2,动态加载js
<script language="javascript"> //动态加载js文件 //by www.jb200.com $.extend({ includePath: '', include: function(file) { var files = typeof file == "string" ? [file]:file; for (var i = 0; i < files.length; i++) { var name = files[i].replace(/^s|s$/g, ""); var att = name.split('.'); var ext = att[att.length - 1].toLowerCase(); var isCSS = ext == "css"; var tag = isCSS ? "link" : "script"; var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' "; var link = (isCSS ? "href" : "src") + "='" + $.includePath + name + "'"; if ($(tag + "[" + link + "]").length == 0) document.write("<" + tag + attr + link + "></" + tag + ">"); } } }); //使用方法 $.includePath = 'http://www.jb200.com/jb/js/'; $.include(['json2.js', 'jquery.tree.js', 'jquery.tree.css']); </script>