Search code examples
javascripthtmlanchorhref

how to utilize javascript in the anchor href and not navigate away from the page


I need to load some dependency java-scripts onto a page if they don't already exist, through java-script. This is done by checking to see if variables are defined, if they are not then generate a script element and add it to the head of the page.

It works the way I'd expect in Chrome. It seems to open a new window when I call the code directly in the href in IE/Firefox. Oddly it works the way I'd expect when I call it indirectly in the href. Here's a trimmed example showing the behaviors (with loading jquery)

<!DOCTYPE html>
<html>
<head>

    <script>
    function test(){
        if (typeof jQuery == 'undefined') {
            var js = document.createElement('script');
            js.setAttribute('type','text/javascript');
            js.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
            var head= document.getElementsByTagName('head')[0];
            head.appendChild(js);
        }
    }
    </script>
</head>

<body>

 <a href="javascript: if (typeof jQuery == 'undefined') {var js = document.createElement('script');js.setAttribute('type','text/javascript');js.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');var head= document.getElementsByTagName('head')[0];head.appendChild(js);}"> navigates to new page </a> 
 |
 <a href="javascript: test();">executes on page</a>

</body>
</html>

If you view this page you'll notice the second link actually loads jquery and puts it on the dom. It also works in chrome. On IE/FF you'll navigate to a new page with <body>[object HTMLScriptElement]</body> as the body contents.

I am perplexed as to why it behaves differently for the second link, and am looking for a solution.

FYI: The reason this needs to be executed in a url is because I'm actually calling this within an AS2 SWF using getURL(), and I cannot alter the pages html to include the java-scripts necessary.


Solution

  • Just add

    return false;
    

    at the end of your code in the href attribute, it will cancel anchor default behaviour, which to navigate to an other URL