简体   繁体   中英

Call javascript file and function, when an image is clicked

I am trying to run an external script that I cannot edit. Currently I am calling upon the script when the page loads. This slows my site down. I would like to instead call the javascript file and run the function when it is clicked. I made it a little faster by calling the function, when clicked. However, it still calls the javascript file because I don't know how to make it call that and the function, when clicked. I spent a few hours reading and trying to find a similar request on Google with no success.

Below you will see what I have came up with so far.

<div id="myFunctionID" style="background: url('http://example.com/button.png') repeat
 scroll 0 0 transparent; width: 100px; height: 50px; cursor: pointer; position:fixed; 
 bottom:0; left:0;">
</div>
<script type="text/javascript" src="https://externalScript.js"></script>

Please help me load the JS file and the myFunctionID , when the button image is clicked.

Using javascript (Quoted from JavaScript - function to load external JS files is needed )

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

Using jquery

$("button").click(function(){
  $.getScript("pathto/external.js");
}); 

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