Chris W
Chris W

Reputation: 1302

Redirect when target page is fully loaded

I am trying to implement a affiliate link on my website. I used to do it with JavaScript, but I would like to keep the link in the controller and not hand it over to JavaScript or html in the future. With JavaScript I waited until the target page was loaded (or at least 1 sec) and redirected the user to that page afterwards.

If I use "redirect_to" in my rails controller it redirects directly, which hides the view completely. Is there any way to use redirect_to after a certain amount of time so at least my view shows up or after the target page has fully loaded?

Code example below:

def index
   redirect_to www.google.com
end

Upvotes: 0

Views: 928

Answers (2)

heading_to_tahiti
heading_to_tahiti

Reputation: 795

You can use the Ruby Sleep method, just know that it is wasting resources and would not achieve your desired effect.

def index
   sleep 3
   redirect_to www.google.com
end

A JS solution would be a higher performing solution. If you are worried about users viewing the link than I would suggest this approach. Use JS to detect when the page loads, and have it wait for whatever amount of time your users need to view before redirection. Then use JS to redirect to a different controller action on your site that will have the direct redirect. This will ensure the page loads for the user before redirect, the user has enough time to view what is on that page, and your affiliate link is in Ruby not JS such as:

def redirect_to_affiliate
   redirect_to www.google.com
end

Upvotes: 1

dax
dax

Reputation: 10997

So the action is triggered when a user clicks the affiliate link?

There are other ways, but i don't see why this wouldn't work:

def affiliate_link
  sleep 2 # or whatever you deem appropriate

  # some other code
  redirect_to some_path
end

Upvotes: 0

Related Questions