Endlessly refreshing occurs when attempting to load a separate CSS stylesheet using document.write

I am attempting to implement two separate stylesheets on my WordPress blog - one for web access and another for our iOS app. Currently, we are adding ?app=true to the URL when accessing content through the app in order to distinguish between the two. Using a JSON API plugin, the app pulls blog posts to display them within a web view interface.

Within my WordPress blog, I have integrated JavaScript that detects the presence of ?app=true in the URL to dynamically load the appropriate 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 script is included in the header.php file of my WordPress theme.

The stylesheet I want to use, named appstyle.css, resides in the same directory as header.php.

However, there is an issue with the code causing the browser page to reload indefinitely. This problem seems related to the document.write function, since removing it resolves the issue (although the appstyle.css is not loaded).

I also attempted the following if statement:

if(window.location.search.indexOf('?app=true') === 0) 

but it did not yield any different results.

Are there more effective methods for loading distinct stylesheets based on whether they are accessed via the iOS app or web? Could there be an error in my implementation?

Answer №1

Give this a shot:

Check if location equals window.location

Try running the above code snippet in your browser console.

When executed, it should return true, indicating that the global variable location is already assigned to the current location object of window. Modifying this variable by assigning a new value will cause the page to reload.

To resolve this issue, simply use a different variable name like so:

var currentLocation = window.location.href;

Alternatively, encapsulate your code within a self-invoking function to keep it separate 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" />');
  }
}());

Answer №2

An error in the syntax is present on this line:

document.write("<link rel="stylesheet" type="text/css" href="appstyle.css" />");

To resolve it, consider using this corrected version:

document.write('<link rel="stylesheet" type="text/css" href="appstyle.css" />');

Alternatively, ensure proper escaping like this:

document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"appstyle.css\" />");

Answer №3

When utilizing document.write, make sure to remember to invoke document.close() upon loading or shortly afterwards.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Harmonize useState with the DOM

I'm encountering an issue with updating my trips array using the search input. Each time I try to update it, I seem to be getting the previous state. For example, if I search for "a", nothing changes, but when I then search for "ab", I see trips filte ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

Conceal Cash on Delivery Payment Method by Adding a Custom Button on Individual Product Pages in WordPress

Exclude COD Option From Checkout Page I am looking to add a custom button on the single product page in WordPress. When users click on the customize button and then add the product to the cart, they will be directed to the checkout page. On the checkout p ...

What is the proper way to select this checkbox using Capybara in Ruby?

Is there a way to successfully check this checkbox?view image description I attempted the following: within('div[id="modalPersistEtapa"]') do element = @driver.find_element(:xpath, '//*[@id="2018_4"]/ ...

Adding a text field to the end of a UICollectionView: A step-by-step guide

One of the features I'm currently working on is an entry field where users can input tags. As soon as a tag is recognized, it gets transformed into a UICollectionViewCell to enhance its appearance. For example: Now, I am looking to enable users to a ...

ways to change date format in a React.js application using JavaScript

<b>Choose Date and Time</b><br/> <DateTimeField onChange={this.clockevent} format={"x"}/> clockevent=(newDate)=>{ var dateVal ="/Date("+newDate+")/"; var date = new Date(parseFloat(dateVal.substr(6))); console.log( ...

Adjusting the alignment of Bootstrap navbar items upon clicking the toggle button

When I click the toggle button on a small screen, my navbar items appear below the search bar instead of aligning with the home and about elements. Below is an image depicting this issue: https://i.stack.imgur.com/4rabW.png Below is the HTML code structu ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...

Puppeteer throwing an error when querying selectors cannot be done (TypeError: selector.startsWith is not a supported function)

I recently installed Puppeteer and ran into an issue when trying to query a selector. I keep receiving a TypeError: selector.startsWith is not a function error. I attempted to resolve the problem by tweaking the core code and adding toString(), but unfort ...

Assistance with CSS Flexbox: How to align items in a grid format (images, titles, text)

I'm currently working on constructing the layout displayed in the image below. The aim is to have the image on the left with a fixed width, while the text on the right adjusts to the available width. Furthermore, the objective is for these items to s ...

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Optimizing CSS table styles for larger cell width

In my CSS file, I have defined the following style: .ES{ max-width:20px; word-wrap:break-word; } However, when I apply this to my table... <table border="1" cellpadding="2" class="ES" > <tr> <td><input name="rbeso" type="radio" ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

How can AJAX be used for form validation prior to submission?

Currently, I am facing an issue with validation on the client side when making an ajax cross-domain request to my PHP server page. I have a standard HTML form that posts input fields such as name, last name, and message. Here is an example of my form on th ...

Use jQuery to retrieve HTML content excluding comments

Take a look at the code snippet below. HTML: <div> <p>sdfsdfsfsf</p> <!--<p>testing</p>--> </div> JQUERY $(document).ready(function(){ alert($("div").html()); }); OUTPUT <p>sdfsdfsfsf</p> & ...

Is there a way to convert a button into clickable text that performs the same function as the original button?

Seeking a solution to transform a button into clickable text with the same functionality. Explored resources like Google, StackOverFlow, and Youtube for answers. This is the current code snippet representing the button: <button onclick="mainApp.l ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...

The onClick event handler is triggered on page load instead of waiting for a click

Recently delving into React, I encountered an issue while attempting to call a function set as a prop. Take a look at my component below: class SamplesInnerLrg extends Component { playSampleAction(sample,sampleId) { console.log(sample); } ...