当条件为真时如何在头部分中包含脚本文件?

问题描述 投票:0回答:1

如果条件为真,我试图将jquery包括到部分中。由于某些原因,脚本对我不起作用,不确定是什么错误

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();   

感谢您的任何帮助

javascript
1个回答
0
投票
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");
© www.soinside.com 2019 - 2024. All rights reserved.