我想在事件上添加某些javascript文件,比如點擊。我試圖使用JavaScript來使用相同的事件,只有當它被觸發。這是因爲腳本會減慢頁面加載速度,否則就不需要腳本。在事件上加載腳本並觸發相同的事件
我可以直接將腳本移動到頁腳並進行全部設置,也可以通過僅在需要時才加載才能通過事件觸發進行設置嗎?下面是我到目前爲止有:
HTML:
<a id="customId" href="#myLink"></a>
的Javascript:
$(document).ready(function() {
//The async addition
var myJS = {
lazyload : function(scriptSrc) {
if(!this.isPresent(scriptSrc)){
var scriptTag = document.createElement('script');
scriptTag.src = scriptSrc;
scriptTag.async = true;
document.getElementsByTagName('head')[0].appendChild(scriptTag);
}
return false;
}
};
//The event trigger needs to do something using the said script
if($('#customId')){
//Approach 1:
var mapEl = document.getElementById("customId");
mapEl.addEventListener("click", customEventHandler, false);
//mapEl.dispatchEvent(event);
//*where
customEventHandler : function(e){
e.preventDefault;
myJS.lazyload('/jsfile.js');
// Update or use link relative #href (not complete path) and use the javascript without navigating out of page.
//e.currentTarget.dispatchEvent(?);
}
//2nd attempt: Adds the script, but not able to trigger event to use JS
$('#customId').click(function(event) {
event.preventDefault();
myJS.lazyload('/jsfile.js');
//Either approach:
//Trigger the custom event to do an actual click after doing the lazy load, using the JS file
(click); $('#customId').trigger('click'); //Is this correct on same element ID
});
}
}
這種方法會導致對元素進行遞歸「點擊」嗎? – guest271314
我不希望它是遞歸的,只是做自定義腳本添加,然後導航到相對鏈接....也許它比我看到更簡單? –
你是什麼意思_「,然後導航到相關鏈接。」_?加載'script'執行什麼任務? – guest271314