首页 > 代码库 > javascript实现js脚本的的异步加载

javascript实现js脚本的的异步加载

javascript实现js脚本的的异步加载,和图片的异步加载稍有不同,script的异步加载需要借助dom,因此有了局限性

<html>
	<head>
		<meta charset="utf-8" />
		<title>Javascript</title>
		<meta http-equiv="X-UA-Compatible" content="IE=7">
	</head>
	<body>
		
		<script type="text/javascript" charset="utf-8">

			function loadScript(url,callback)
			{
				

				var script = document.createElement(‘script‘);
				if(!!document.setAttribute)
				{

					script.setAttribute(‘type‘,‘text/javascript‘);
					script.setAttribute(‘charset‘,‘utf-8‘);
					script.setAttribute(‘language‘,‘javascript‘);
				}else{
					script[‘type‘] =‘text/javascript‘;
					script[‘charset‘] = ‘utf-8‘;
					script[‘language‘] = ‘javascript‘;
					
				}

				if (!!script.readyState)
				{

					script.onreadystatechange = function()
					{ 
					
						if (script.readyState == "loaded" ||script.readyState == "complete")
						{ 
							script.onreadystatechange = null; 
							callback(script); 
						} 
					}; 
				}else{

					script.onload = function()
					{
						script.onload = null;
						callback(script);
					}
				}

				script[‘src‘] = url;

				document.head.appendChild(script);
			}

			loadScript(‘https://fbstatic-a.akamaihd.net/rsrc.php/v2/yv/r/wgFc3t0g5gk.js‘,function(script){
				console.log(script);
			});
			
		</script>
	</body>
</html>


javascript实现js脚本的的异步加载