dennis96411
dennis96411

Reputation: 127

Why does my JavaScript not execute in order?

I don't understand why my code isn't running in order... The code below doesn't execute the document.write part, but it executes the part after it just fine. I think it has something to do with the timing, giving the browser to execute the . I tried using setTimeout in some parts, but it's either not working, or I'm doing it wrong.

function isBrowserMobile()
{
    var iPadAgent = navigator.userAgent.match(/iPad/i) != null;
    var iPodAgent = navigator.userAgent.match(/iPhone/i) != null;
    var AndroidAgent = navigator.userAgent.match(/Android/i) != null;
    var webOSAgent = navigator.userAgent.match(/webOS/i) != null;
    if (iPadAgent || iPodAgent || AndroidAgent || webOSAgent)
    {
       document.write("<body bgcolor='Orange'><b>Mobile browser detected!</b></body>");
       var choice = confirm("Do you want to visit the mobile site?")
       if (choice)
           mobile();
       else
           desktop();
    }
}

Upvotes: 1

Views: 490

Answers (2)

Alvin Wong
Alvin Wong

Reputation: 12420

EDIT:

I suggest you not to use document.write but to use DOM, like the following:

document.body.style.backgroundColor='Orange';
document.body.innerHTML='This is a text';

And when testing your code in a desktop browser you can add true || to the start of the if condition.

My original answer used innerText which is not a standard

Upvotes: 1

RobG
RobG

Reputation: 147403

Browsers rarely update the page before a function has finished processing. So the document.write has been executed, but the result may not be displayed until the function is complete.

As minitech said, it's a pretty rubbish function anyway. You should be asking based on screen size, not UA sniffing.

Note that if the function is run after the document has finished loading, the call to document.write will wipe out the entire contents of the document, including the script.

Upvotes: 0

Related Questions