user3202909
user3202909

Reputation: 33

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!

Upvotes: 0

Views: 904

Answers (3)

Scopey
Scopey

Reputation: 6319

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.

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42736

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");
}

Upvotes: 2

Vennik
Vennik

Reputation: 565

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 {

}

Upvotes: 0

Related Questions