[英]DYnamically add a javascript
I have a situation in my code where i check if my webpage is being viewed by a mobile browser or a desktop browser and based on that i want to load the javascript files that contain the events. 我的代码中有一种情况,我检查我的网页是否正在由移动浏览器或桌面浏览器查看,并基于此我想加载包含事件的javascript文件。 I have the following code
我有以下代码
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
addJavascript('js/mobileEvents.js','body');
}
else{
addJavascript('js/mouseEvents.js','body');
}
My addJavascript function is as follows 我的addJavascript函数如下
function addJavascript(jsname,pos)
{
var oHead = document.getElementsByTagName(pos).item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src=jsname;
oHead.appendChild(oScript);
}
But the scripts doesnt load. 但是脚本不会加载。 Please help me.
请帮我。
In plain JS: 在普通的JS中:
function addJavascript(url){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
var scriptNode = document.getElementsByTagName('script')[0];
scriptNode.parentElement.insertBefore(script, scriptNode);
}
If you have jQuery in the page just use: 如果页面中有jQuery,请使用:
$.getScript(url);
This is a jsFiddle demo that will load different jQuery-UI lib version based on the browser: http://jsfiddle.net/8fC6w/ 这是一个jsFiddle演示,它将基于浏览器加载不同的jQuery-UI lib版本: http : //jsfiddle.net/8fC6w/
如果可以访问HTML,则可以在头中定义jsname
,然后只需将script标签添加到HTML的正文中即可。
<script>document.write('<script src="'+jsname+'"></script>')</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.