gpt4 book ai didi

javascript - 根据窗口大小加载jquery

转载 作者:行者123 更新时间:2023-11-30 17:29:54 25 4
gpt4 key购买 nike

我是 javascript 的新手,正在努力解决这个基本问题 - 我只想在窗口大小低于特定阈值时加载 jQuery(即,移动版本不需要它)。对于桌面版本,jQuery 必须在 <head> 中加载而不是 <body> ,因为首屏内容需要它。

我已经测试了循环,并且在页面上打印了屏幕宽度,但是 jQuery 没有加载。我确定这是一个基本的语法问题,但我看不到它!非常感激任何的帮助。 :)

   <script type="text/javascript"> 
function loadjsfile(filename){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
}

var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
if (w > 899){
document.write("screen Width: " + w);
loadjsfile("http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js");
}
</script>

最佳答案

您已经创建了包含脚本标记对象的 fileref 变量,但您从未将它添加到 DOM,因此它永远不会加载。

function loadjsfile(filename){
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);

//add this line
document.getElementsByTagName('head')[0].appendChild(fileref);
}

关于javascript - 根据窗口大小加载jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23354616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com