Search code examples
javascriptonclickgetelementbyidtypeofgetelementsbytagname

loading script only once on click event


I've hacked together vanilla javascript to load external script on click event.

var searchLabel = document.getElementById('search-toggle-label');
searchLabel.onclick = function(){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "wp-content/themes/2016/js/cse.js."; 
    document.getElementsByTagName("head")[0].appendChild(script);
    return false;
}

But it keeps loading the same script every time on click event.

So I threw in an if statement to check for value & type. "==="

var searchLabel = document.getElementById('search-toggle-label');
if (typeof searchLabel === 'undefined') {
    searchLabel.onclick = function() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "wp-content/themes/2016/js/cse.js."; 
        document.getElementsByTagName("head")[0].appendChild(script);
        return false;
    }
}
else {
    alert('loaded already');
}

Obviously, this is wrong since I get an alert on page load & on click event, the script does not load.

I am stumped. I know there is an easy solution using jQuery but I am trying to actually learn to write javascript.

Any help will be greatly appreciated.


Solution

  • Remove the event listener once it has fired:

    var searchLabel = document.getElementById('search-toggle-label');
    searchLabel.addEventListener('click', loadScript('wp-content/themes/2016/js/cse.js'), false);
    
    function loadScript(src){
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = src; 
        document.head.append(script);
        return searchLabel.removeEventListener('click', loadScript, false);
    }