One of the Javascript files on my site is screwing up the display on iPad (Mobile Safari). I want to remove the file only on an iPad and serve it for every other browser.
I've got the following javascript:
<script type="text/javascript">
<![CDATA[
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
if((navigator.userAgent.match(/iPad/i))
{
removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page for ipad
}
]]
</script>
Firstly - is the above Javascript valid? (I have a limited knowledge)
Secondly - is this the best way to do it?
If you aren't using php or something else where this is a lot easier, you should do it the other way around, where you conditionally load the files into the head of the document, if the browser isn't an ipad.
function loadjscssfile(filename, filetype) {
if (filetype == "js") { //if filename is a external JavaScript file
var fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype == "css") { //if filename is an external CSS file
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref != "undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
var isiPad = navigator.userAgent.match(/iPad/i) != null;
if (!isiPad) {
//load js OR css files
}
I fixed this by finding the offending JS function and adding:
&& navigator.userAgent.match(/ipad/i) == null
Simple is good
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.