附加&LT;脚本SRC =&QUOT;&QUOT;&GT;&LT; / SCRIPT&GT;将头根据屏幕宽度 [英] appending <script src=""></script> to head based on screen width
问题描述
我需要这样的东西容易:
i need something easy like this:
<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "mobile.html";
}
//-->
</script>
但不是重定向我需要&LT; SCRIPT SRC =js.js&GT;&LT; / SCRIPT&GT;
中追加&LT; HEAD&GT;&LT; /头&GT;
这可能吗?
推荐答案
请参阅它在行动:<大骨节病> 简短的演示 骨节病>
您可以定义一个函数,就像这样:
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");
如果您还需要从头
删除脚本(例如,基于其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).
如果你需要让你可以使用窗口大小 $(窗口).WIDTH()
(使用jQuery)。
如果你想要一个jQuery的自由的解决方案,来看看 <一个href=\"http://stackoverflow.com/questions/3437786/how-to-get-web-page-size-browser-window-size-screen-size-in-a-cross-browser-wa\">this回答 作为跨浏览器的替代品。
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.
这篇关于附加&LT;脚本SRC =&QUOT;&QUOT;&GT;&LT; / SCRIPT&GT;将头根据屏幕宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!