附加 <script src="></script>根据屏幕宽度显示头部

2022-01-22 00:00:00 append jquery javascript

我需要这样简单的东西:

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.

相关文章