问题描述
我需要这样简单的东西:
i need something easy like this:
<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "mobile.html";
}
//-->
</script>
但不是重定向,我需要将 <script src="js.js"></script> 附加到 <head></头>
but instead of a redirect i'd need <script src="js.js"></script> to be appended in <head></head>
这可能吗?
推荐答案
实际操作:简短演示
你可以定义一个函数,像这样:
You can define a function, like this:
function appendScript(pathToScript) {
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.src = pathToScript;
head.appendChild(js);
}
然后用适当的参数调用它(例如根据屏幕大小),像这样:
And then call it with the appropriate argument (e.g. according to screen size), like this:
appendScript("path/to/file.js");
<小时>
如果您还需要从 head 中删除脚本(例如,基于其 'src' 属性),您可以定义一个函数,如下所示:
If you also need to remove a script from head (e.g. based on its 'src' attribute), you can define a function, like this:
function removeScript(pathToScript) {
var head = document.getElementsByTagName("head")[0];
var scripts = head.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var js = scripts[i];
if (js.src == pathToScript) {
head.removeChild(js);
break;
}
}
}
然后用适当的参数调用它(例如根据屏幕大小),像这样:
And then call it with the appropriate argument (e.g. according to screen size), like this:
removeScript("path/to/file.js");
<小时>
另外,请注意,使用 screen.width 返回用户屏幕的大小(不是浏览器窗口的宽度).
Also, note that using screen.width returns the size of the user's screen (not the browser-window's width).
如果您需要获取窗口大小,可以使用 $(window).width()(使用 jQuery).如果您想要无 jQuery"解决方案,请查看 this answer 用于跨浏览器的替代方案.
If you need to get the window size you can use $(window).width() (using jQuery).
If you want a "jQuery-free" solution, take a look at this answer for cross-browser alternatives.
这篇关于附加 <script src="></script>根据屏幕宽度显示头部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)