简体   繁体   中英

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. 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

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.

Try with LABjs

This project is a simple little tool for being able to load javascript files dynamically

In plain 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:

$.getScript(url);

This is a jsFiddle demo that will load different jQuery-UI lib version based on the browser: http://jsfiddle.net/8fC6w/

如果可以访问HTML,则可以在头中定义jsname ,然后只需将script标签添加到HTML的正文中即可。

<script>document.write('<script src="'+jsname+'"></script>')</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM