1

I have an asp website and am trying to automatically generate some javascript. I have an ashx file that generates the javascript and then I would like to like to this javascript in a href. I have seen it done on other websites but can't work out how its done.

The ashx file called 'Hello.ashx' outputs something like

alert("Hello World");

I am trying to execute this as below

<a href="Hello.ashx">Text</a>

How is this done? Is is actually possible or are other websites using some trick?

Your help is greatly appreciated

1 Answer 1

3

You want to load the javascript file when the anchor is clicked:

function loadjs() {
    var head = document.getElementsByTagName('head');
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', 'Hello.ashx');
    head[0].appendChild(s);
    return false;
}

<a href="javascript: loadjs()">Text</a>

If you're using jQuery a better approach is:

<a href="Hello.ashx" id="hello">Text</a>

$(function(){ $('#hello').click(loadjs); });

To load it once:

var _myscript = null;
function loadjs() {
    if (_myscript != null) return false;
    _myscript = document.createElement('script');
    //...
}
Sign up to request clarification or add additional context in comments.

1 Comment

How would I remove any old imports, as multiple clicks on the link cause multiple imports

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.