My JavaScript code detects the useragent for Android, iPhone, or iPod and loads specific JavaScript files accordingly. The code functions perfectly, but I noticed that having two 'createScript' functions with different names performing the same task is redundant. Therefore, I attempted to use a parameter/variable instead, but without success.
<script type="text/javascript">
if(navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)) {
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function createScript(scriptname)
{
var oNode=document.createElement("script");
document.getElementsByTagName("body")[0].appendChild(oNode);
oNode.setAttribute("id", "newScript", 0);
oNode.setAttribute("type", "text/javascript", 0);
oNode.setAttribute("src", scriptname, 0);
}
createscriptlibrary = createScript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js");
createmyscript = createScript("nav.js");
addLoadEvent(createscriptlibrary);
addLoadEvent(createmyscript);
}
</script>
I've been attempting to modify the code above by using parameters in the 'createScript' function, but it's not functioning as intended:
<script type="text/javascript">
if(navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function createScript(scriptname)
{
var oNode=document.createElement("script");
document.getElementsByTagName("body")[0].appendChild(oNode);
oNode.setAttribute("id", "newScript", 0);
oNode.setAttribute("type", "text/javascript", 0);
oNode.setAttribute("src", + scriptname + , 0);
}
createscriptlibrary = createScript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js");
createmyscript = createScript("nav.js");
addLoadEvent(createscriptlibrary);
addLoadEvent(createmyscript);
}
</script>
If possible, could someone assist me in resolving this issue? Thank you.