简体   繁体   中英

php if - screen width - load js

I'm new to php. I have a doubt, don't know if this can be done, or if it should be done in another way or what. I want to load a JS only if the screen size is higher than x size.

I wrote this but the JS is not being loaded (in fact I want to load a couple of JS):

<script language="javascript">
if (screen.width > 549) {
    <script src='js/jquery-1.8.1.min.js' type='text/javascript'></script>
}

best regards!

php cannot detect a clients screen width/height, that all would have to be done client side.

function addScript(src){
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.src = src;
   document.head.appendChild(script);
} 

if(screen.width > 549){
    addScript("js/jquery-1.8.1.min.js");
    addScript("js/someOtherScript.js");
}

It's cleaner to detect the screen width in JavaScript. Also remember the screensize can change in a session. For example when a user resizes his screen.

Use this in your JavaScript file:

var width = document.body.clientWidth;
if(width > 549) {

} else if(width < 300) {

} else {

}

You cannot determine a clients' browser window size before a client has received a page with PHP.

Technically you could load a page, get javascript to send back the window size and then store it in the session for that user, but I don't really see the point. You're better off either always including the javascript file, or using a javascript library to conditionally add other scripts to the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM