简体   繁体   中英

how to include script file in head section when condition is true?

I am trying to include jquery into section, if condition is true. For some reasons script doesnt work for me, not sure what is wrong

function loadScript() { 
    var currentLocation = String(window.location); 
    var c = currentLocation.includes('test') 

    if(c===true){  
        //document.write('<scr'+'ipt type="text/javascript" src="assets/jquery.js"></scr'+'ipt>');
        console.log(c);
        var head = document.getElementsByTagName('head')[0];  

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = "jquery.js";
        //head.appendChild(script);
        document.getElementsByTagName('head')[0].appendChild(script);
        alert("asdsad");
    }
    else{
      console.log('error');
    }
}

loadScript();   

Any help is appreciated

function loadJQueryIfMatch(keyword) {
    if (window.location.href.includes(keyword)) {
        var script_tag = document.createElement('script');
        script_tag.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js');
        document.head.appendChild(script_tag);
    }

}

loadJQueryIfMatch("test");

Your code is fine currentLocation.includes('test') is a case sensitive only.

load script in codepen

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