javascript动态加载js脚本
1、直接document.write
代码如下 | 复制代码 |
<script language="javascript"> document.write("<script src='test.js'></script>"); </script> |
2、动态改变已有script的src属性
代码如下 | 复制代码 |
<script src='' id="s1"></script> <script language="javascript"> s1.src="test.js" </script> |
3、动态创建script元素
代码如下 | 复制代码 |
function require(url, options){ var head, node, isOpera; isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]'; options.success = options.success || function(){}; options.error = options.error || function(){}; options.type = options.type || 'text/javascript'; options.charset = options.charset || 'utf-8'; options.async = options.async || true; head = document.getElementsByTagName("head")[0]; node = document.createElement(//javascript/i.test(options.type) ? 'script' : 'style'); node.type = options.type; node.charset = options.charset; node.async = options.async; node.src = url; if (node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera){ node.attachEvent('onreadystatechange', function(){ if(!node.readyState || node.readyState == "loaded" || node.readyState == "complete"){ options.success(); } }); }else{ node.addEventListener('load', options.success, false); node.addEventListener('error', options.error, false); } head.appendChild(node); } |
IE不支持加载失败检测
代码如下 | 复制代码 |
require('http://code.jquery.com/jquery-1.7.3.min.js', { success:function(){ alert('jquery loaded!'); }, error:function(){ alert('jquery load fail!'); } }); |
方法四
代码如下 | 复制代码 |
//动态加载脚本文件 function AddScript(scriptID,scriptSRC) //动态加载脚本内容 function AddScript(scriptID,scriptContent) |