简体   繁体   中英

Run Javascript using onclick?

If I set the following up:

<script type="text/javascript" src="https://test.com/abc"></script> 

Between the head tags, the code runs when the page starts up. Is there any way of stopping this from running during startup and instead running it using the onclick method from a html button?

Take the javascript in your file and wrap it in a function. You can then assign that function to the onclick attribute of a button.

<button onclick="myFunction()">Click Me</button>

And your script

function myFunction() { 
    //your existing code goes here
}

Here's a fiddle .

1- You should try to avoid adding scripts in the head as it makes slow rendering page. If you really need to do so may be you could look for defer / async scripts.

2- You should try to put the script at bottom in order to make browser rendering all the html and css as fast as possible.

3- Finally at the bottom you should call in the load page. For example in jquery.ready like this doc says, search for jquery ready event. In that moment you should add a listener to the button you need by calling a jquery selector on the button, search for jquery selector, finally you add the click event, search for jquery click event, and then you process what you need inside that callback.

Here is a fiddle.

[https://jsfiddle.net/d6zfqpc6/][1]

Jquery acts as a good polyfill also to somethings :).

Although the onclick method is a very nice way, but it is no longer supported .

The addEventListener method is the most suitable and the modern method to do it.

It can be used in two ways:

  1. Connecting an already existing function to an event listener:

     document.getElementByID("clickMe").addEventListener("click", myfunction);
  2. Writing a function within an event listener:

     document.getElementByID("clickMe").addEventListener("click", function() { //a function, for eg.: document.getElementById("p").innerHTML = "Hello World"; });

Here's an example snippet for ease of understanding:

 document.getElementById("clickme").addEventListener("click", function() { document.getElementById("p").innerHTML = "Hello World"; });
 <button id="clickme">Try it</button> <p id="p"></p>

Also, I'd advice you to use the script at the bottom of the page rather than the head, so that the HTML and CSS can load first.


Hope I could help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM