I am trying to have two different stylesheets on my wordpress blog, so that one stylesheet is used when the page is accessed via the web, and the other stylesheet is used when the blog content is accessed via our iOS app. Right now we are appending ?app=true to URL requests from our iOS app in hopes that in our blog we could search for this string and load a different stylesheet. We are using a JSON API plugin so that our iOS app can programmatically pull our blog posts and display them in a web view in the iOS App.
In my wordpress blog I am using javascript that looks for ?app=true in the URL, and if so, load a different stylesheet.
<script language="javascript" type="text/javascript">
var location = window.location.href;
if(location.indexOf("?app=true") > -1) {
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"appstyle.css\" />");
}
</script>
This code is placed within the tags in the header.php file of my wordpress theme.
The stylesheet that I am trying to use is called appstyle.css and is located in the same directory as header.php.
The issue that I'm having is that with this code it reloads the browser page infinitely. The issue seems to be with the document.write function, as without that the webpage loads fine (although it obviously isn't loading the appstyle.css stylesheet).
I have also tried this if statement:
if(window.location.search.indexOf('?app=true') === 0)
but it doesn't seem to make a difference.
Is there a better way to load different stylesheets depending on if it is loaded in an iOS app vs the web? Is there something I am doing wrong in my code?
try:
location === window.location
in the console.
It will output true
. Which shows that the global variable location
is already set and points to the current location
object of window
. With your code you're changing that variable, by assigning a new value, which triggers a browser reload.
To fix it, just use another name for your variable, e.g.:
var currentLocation = window.location.href;
Or put your code in a self-executing function, to separate it from the global scope:
(function (){
var location = window.location.href;
if(location.indexOf('?app=true') > -1) {
document.write('<link rel="stylesheet" type="text/css" href="appstyle.css" />');
}
}());