根据“媒体屏幕”值调用外部JS文件

时间:2022-03-20 11:19:17

I'm trying this but it is not working:

我正在尝试这个,但它不起作用:

<html>
<head>
<script src="js/menu-collapser.js" type="text/javascript" media="media screen and (max-width: 599px)"></script>
</head>
...
</html>

//menu-collapser.js :

//menu-collapser.js:

jQuery(document).ready(function($){
    $('.main-navigation li ul').hide();
    $('.main-navigation li').has('ul').click(function() {
        $(this).children().toggle();
    });
});

Do you have an idea on how to do this in the right way? The script work if used directly in the header with the tags.

您是否知道如何以正确的方式做到这一点?如果标题中直接使用该脚本,则该脚本可以正常工作。

3 个解决方案

#1


15  

You can't do that directly using Javascript <script> tags. Media queries are used in linked CSS files or inline CSS styles. A basic example:

您不能使用Javascript

<link rel="stylesheet" media="screen and (min-width: 900px)" href="desktop.css"/>
<link rel="stylesheet" media="screen and (min-width: 571px)" href="tablet.css"/>
<link rel="stylesheet" media="screen and (max-width: 570px)" href="mobile.css"/>

Or directly in your stylesheets:

或直接在您的样式表中:

@media screen and (max-width: 599px) {
  #mobile {
     display: block;
  }
}

However, you can use an external asset loader/media query library to do this (require.js, modernizr.js, enquire.js and others), In this case, I'm setting an example using enquire.js, as I think it's very effective and doesn't require jQuery by default:

但是,您可以使用外部资产加载器/媒体查询库来执行此操作(require.js,modernizr.js,enquire.js等),在这种情况下,我正在使用enquire.js设置示例,我认为它非常有效,默认情况下不需要jQuery:

Full example

1) Include enquire.js (available here):

1)包括enquire.js(可在此处获得):

<script type="text/javascript" src="/js/enquire.js"></script>

2) Create a load function - to load JS files:

2)创建一个加载函数 - 加载JS文件:

<script type="text/javascript">

// This loads JS files in the head element
    function loadJS(url)
    {
        // adding the script tag to the head
       var head = document.getElementsByTagName('head')[0];
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = url;

       // fire the loading
       head.appendChild(script);
    }

</script>

3) Fire enquire.js and listen for media query changes (both on-load and on-resize):

3)Fire enquire.js并监听媒体查询更改(包括加载和调整大小):

<script type="text/javascript">

    enquire.register("screen and (max-width: 599px)", {
        match : function() {
            // Load a mobile JS file
            loadJS('mobile.js');
        }
    }).listen();


    enquire.register("screen and (min-width: 600px) and (max-width: 899px)", {
        match : function() {
            // Load a tablet JS file
            loadJS('tablet.js');
            //console.log('tablet loaded');
        }
    }).listen();


    enquire.register("screen and (min-width: 900px)", {
        match : function() {
            // Load a desktop JS file
            loadJS('desktop.js');
            //console.log('desktop loaded');
        }
    }).listen();
</script>


Putting it all together

Using a simple HTML page with enquire.js loaded from an external file:

使用从外部文件加载的enquire.js的简单HTML页面:

<html>
<head>

<script type="text/javascript" src="/enquire.js"></script>

<script type="text/javascript">

// This loads JS files in the head element
    function loadJS(url)
    {
        // adding the script tag to the head
       var head = document.getElementsByTagName('head')[0];
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = url;

       // fire the loading
       head.appendChild(script);
    }

</script>

<style>

    body {
      font-family: arial;
    }
    h1 {
      font-size: 50pt;
    }

    #mobile {
      display: none;
    }
    #tablet {
      display: none;
    }
    #desktop {
      display: none;
    }

    @media screen and (max-width: 599px) {
        #mobile {
            display: block;
        }
    }

    @media screen and (min-width: 600px) and (max-width: 899px) {
        #tablet {
            display: block;
        }
    }

    @media screen and (min-width: 900px) {
        #desktop {
            display: block;
        }
    }   

</style>

</head>
<body>

    <div id="desktop">
        <h1>Desktop</h1>
    </div>

    <div id="tablet">
        <h1>Tablet</h1>
    </div>

    <div id="mobile">
        <h1>Mobile</h1>
    </div>

    <script type="text/javascript">

        enquire.register("screen and (max-width: 599px)", {
            match : function() {
                // Load a JS file
                loadJS('mobile.js');
            }
        }).listen();


        enquire.register("screen and (min-width: 600px) and (max-width: 899px)", {
            match : function() {
                loadJS('tablet.js');
                //console.log('tablet loaded');
            }
        }).listen();


        enquire.register("screen and (min-width: 900px)", {
            match : function() {
                loadJS('desktop.js');
                //console.log('desktop loaded');
            }
        }).listen();

    </script>
</body>
</html>

In addition to loading JS files, you could create a CSS loader too, which would work in the same way (conditionally), but that defeats the object of using @media in CSS. It's worth reading the usage explanations for enquire.js, as it can do a lot more than I've illustrated here.

除了加载JS文件之外,您还可以创建一个CSS加载器,它可以以相同的方式(有条件地)工作,但是这会破坏在CSS中使用@media的对象。值得一读enquire.js的用法说明,因为它可以做的比我在这里说明的要多得多。

Caveat: Nothing above uses jQuery, but you could take advantage of some of the functions it offers; loading scripts for example - or executing other functions that you need to.

警告:上面没有使用jQuery,但你可以利用它提供的一些功能;例如加载脚本 - 或执行您需要的其他功能。

#2


4  

Why not just load in a script conditionally?

为什么不有条件地加载脚本?

(function() {
    if( window.innerWidth > 600 ) {
        var theScript = document.createElement('script');
            theScript.type = 'text/javascript';
            theScript.src = 'js/menu-collapser.js';

        var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(theScript, s);
    }
})();

Or better yet, only execute the code if the window.innerWidth > 600 ? Anyway, there are a lot of solutions you can use.

或者更好的是,如果window.innerWidth> 600,只执行代码?无论如何,你可以使用很多解决方案。

#3


1  

media is not a valid attribute for <script>, check it here.

media不是

So you should detect media types by manually than load the script dynamically.

因此,您应该手动检测媒体类型,而不是动态加载脚本。

There is a plug-in for css media detection in javascript, you can use it.

在javascript中有一个用于css媒体检测的插件,你可以使用它。

<script type="text/javascript" src="js/mediatypechecker.js"></script>

$(function() {
    if(IsMediaType('screen') > 0 && parseInt(screen.width) < 599) {
        $.getSscript("js/menu-collapser.js");
    }
});

#1


15  

You can't do that directly using Javascript <script> tags. Media queries are used in linked CSS files or inline CSS styles. A basic example:

您不能使用Javascript

<link rel="stylesheet" media="screen and (min-width: 900px)" href="desktop.css"/>
<link rel="stylesheet" media="screen and (min-width: 571px)" href="tablet.css"/>
<link rel="stylesheet" media="screen and (max-width: 570px)" href="mobile.css"/>

Or directly in your stylesheets:

或直接在您的样式表中:

@media screen and (max-width: 599px) {
  #mobile {
     display: block;
  }
}

However, you can use an external asset loader/media query library to do this (require.js, modernizr.js, enquire.js and others), In this case, I'm setting an example using enquire.js, as I think it's very effective and doesn't require jQuery by default:

但是,您可以使用外部资产加载器/媒体查询库来执行此操作(require.js,modernizr.js,enquire.js等),在这种情况下,我正在使用enquire.js设置示例,我认为它非常有效,默认情况下不需要jQuery:

Full example

1) Include enquire.js (available here):

1)包括enquire.js(可在此处获得):

<script type="text/javascript" src="/js/enquire.js"></script>

2) Create a load function - to load JS files:

2)创建一个加载函数 - 加载JS文件:

<script type="text/javascript">

// This loads JS files in the head element
    function loadJS(url)
    {
        // adding the script tag to the head
       var head = document.getElementsByTagName('head')[0];
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = url;

       // fire the loading
       head.appendChild(script);
    }

</script>

3) Fire enquire.js and listen for media query changes (both on-load and on-resize):

3)Fire enquire.js并监听媒体查询更改(包括加载和调整大小):

<script type="text/javascript">

    enquire.register("screen and (max-width: 599px)", {
        match : function() {
            // Load a mobile JS file
            loadJS('mobile.js');
        }
    }).listen();


    enquire.register("screen and (min-width: 600px) and (max-width: 899px)", {
        match : function() {
            // Load a tablet JS file
            loadJS('tablet.js');
            //console.log('tablet loaded');
        }
    }).listen();


    enquire.register("screen and (min-width: 900px)", {
        match : function() {
            // Load a desktop JS file
            loadJS('desktop.js');
            //console.log('desktop loaded');
        }
    }).listen();
</script>


Putting it all together

Using a simple HTML page with enquire.js loaded from an external file:

使用从外部文件加载的enquire.js的简单HTML页面:

<html>
<head>

<script type="text/javascript" src="/enquire.js"></script>

<script type="text/javascript">

// This loads JS files in the head element
    function loadJS(url)
    {
        // adding the script tag to the head
       var head = document.getElementsByTagName('head')[0];
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = url;

       // fire the loading
       head.appendChild(script);
    }

</script>

<style>

    body {
      font-family: arial;
    }
    h1 {
      font-size: 50pt;
    }

    #mobile {
      display: none;
    }
    #tablet {
      display: none;
    }
    #desktop {
      display: none;
    }

    @media screen and (max-width: 599px) {
        #mobile {
            display: block;
        }
    }

    @media screen and (min-width: 600px) and (max-width: 899px) {
        #tablet {
            display: block;
        }
    }

    @media screen and (min-width: 900px) {
        #desktop {
            display: block;
        }
    }   

</style>

</head>
<body>

    <div id="desktop">
        <h1>Desktop</h1>
    </div>

    <div id="tablet">
        <h1>Tablet</h1>
    </div>

    <div id="mobile">
        <h1>Mobile</h1>
    </div>

    <script type="text/javascript">

        enquire.register("screen and (max-width: 599px)", {
            match : function() {
                // Load a JS file
                loadJS('mobile.js');
            }
        }).listen();


        enquire.register("screen and (min-width: 600px) and (max-width: 899px)", {
            match : function() {
                loadJS('tablet.js');
                //console.log('tablet loaded');
            }
        }).listen();


        enquire.register("screen and (min-width: 900px)", {
            match : function() {
                loadJS('desktop.js');
                //console.log('desktop loaded');
            }
        }).listen();

    </script>
</body>
</html>

In addition to loading JS files, you could create a CSS loader too, which would work in the same way (conditionally), but that defeats the object of using @media in CSS. It's worth reading the usage explanations for enquire.js, as it can do a lot more than I've illustrated here.

除了加载JS文件之外,您还可以创建一个CSS加载器,它可以以相同的方式(有条件地)工作,但是这会破坏在CSS中使用@media的对象。值得一读enquire.js的用法说明,因为它可以做的比我在这里说明的要多得多。

Caveat: Nothing above uses jQuery, but you could take advantage of some of the functions it offers; loading scripts for example - or executing other functions that you need to.

警告:上面没有使用jQuery,但你可以利用它提供的一些功能;例如加载脚本 - 或执行您需要的其他功能。

#2


4  

Why not just load in a script conditionally?

为什么不有条件地加载脚本?

(function() {
    if( window.innerWidth > 600 ) {
        var theScript = document.createElement('script');
            theScript.type = 'text/javascript';
            theScript.src = 'js/menu-collapser.js';

        var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(theScript, s);
    }
})();

Or better yet, only execute the code if the window.innerWidth > 600 ? Anyway, there are a lot of solutions you can use.

或者更好的是,如果window.innerWidth> 600,只执行代码?无论如何,你可以使用很多解决方案。

#3


1  

media is not a valid attribute for <script>, check it here.

media不是

So you should detect media types by manually than load the script dynamically.

因此,您应该手动检测媒体类型,而不是动态加载脚本。

There is a plug-in for css media detection in javascript, you can use it.

在javascript中有一个用于css媒体检测的插件,你可以使用它。

<script type="text/javascript" src="js/mediatypechecker.js"></script>

$(function() {
    if(IsMediaType('screen') > 0 && parseInt(screen.width) < 599) {
        $.getSscript("js/menu-collapser.js");
    }
});