0

I was wondering about the syntax of running external .js files, when you do it normally you just do

<script src=http://www.example.com/javascript.js></script>

but when running code in chrome (through the url bar), where the syntax is:

javascript:javascriptcodegoeshere

The <script> tags aren't included, so how can you launch a js file through using that?

1
  • <script> is HTML. The tags tell the browser that the text inside is to be interpreted as JavaScript. What you put in the address bar is a URI. The javascript: URI is not standardized but browsers simply interpret everything following the protocol as JavaScript. Those two are totally different things and ways to "tell" the browser about JavaScript code (although using javascript: URIs became a bad practice). Commented Jun 30, 2013 at 18:30

1 Answer 1

1

You have four options.

  1. You can put the actual code in the <script> block.

    <script>
        javascriptcodegoeshere
    </script>
    
  2. You can save the code in a file and refer to it.

    <script src="http://www.example.com/javascript.js"></script>
    
  3. You can put it as a data URL.

    <script src="data:text/javascript,javascriptcodegoesgere"></script>
    
  4. You can put it in a link if you want the user to launch the code.

    <a href="javascript:javascriptcodegoeshere">link</a>
    
Sign up to request clarification or add additional context in comments.

5 Comments

Just remember that method 4 can only be used inside <body> and requires the user to click the link to ru the code, so does not work for things that must be initialized on page load.
pietu very nice, thanks, can you expand more on how i could call an external .js script through using <a href="javascript:javascriptcodegoeshere">link</a>? thanks :). I'd like the code not to be visible, looks neater.
If the code is any longer then a very short line, it is ill advised to call something via the href="javascript:javascriptgoeshere method. Any thing longer should be placed either in an external file, or in a script tag on the page. Not knowing what, exactly, you are trying to accomplish with javascript makes it tough for me to recommend a best course of action, but I can promise that the answer is almost never using the 4th method in the answer above. HTML is a presentation language and should be kept separate from javascript which is a functional language.
how do i call an external script by using javascript:codegoeshere?
You can't do that directly. I suggest that you take the external script, put it into a file and put everything that is not in a function inside one. Then you can run that code using <a href="javascript:functionName()">link</a>.

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.