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.
我正在尝试运行一个无法编辑的外部脚本。目前我在页面加载时调用脚本。这会减慢我的网站速度。我想调用javascript文件并在单击时运行该函数。单击时调用该函数,我的速度提高了一些。但是,它仍然调用javascript文件,因为我不知道如何调用它和函数,当单击时。我花了几个小时阅读并尝试在Google上找到类似的请求但没有成功。
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.
单击按钮图像时,请帮我加载JS文件和myFunctionID。
1 个解决方案
#1
1
Using javascript (Quoted from JavaScript - function to load external JS files is needed)
使用javascript(引自JavaScript - 需要加载外部JS文件的函数)
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");
});
#1
1
Using javascript (Quoted from JavaScript - function to load external JS files is needed)
使用javascript(引自JavaScript - 需要加载外部JS文件的函数)
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");
});