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

时间:2019-11-20 17:57:23

标签: javascript

如果条件为真,我正在尝试将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();   

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您的代码没问题currentLocation.includes('test')仅区分大小写。

load script in codepen