Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve up different javascript files by browser width

So I want certain Javascript files for certain browser widths. I know that @media serves up specific CSS per browser width and some devices. How would I do something similar for Javascript files, WITHOUT using server side calls?

Is is possible with Javascript to call other Javascript files based on browser width? If so, How?

Thanks in advance.

like image 580
ClosDesign Avatar asked Jan 26 '11 23:01

ClosDesign


People also ask

How do I separate JavaScript files?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can I link multiple JavaScript files to HTML?

yes.. you can have multiple javascripts files in html page.

How do I reduce the number of JavaScript files on my website?

Combine all JavaScript files in one file To minimize the number of HTTP requests you should try combining the content of all your JavaScript files to one bigger file. This isn't always possible with every JavaScript file, though. Try and see how it works out for your site.


2 Answers

var scriptSrc = 'js/defaults.js';
if (screen.width <= 800)
  scriptSrc = 'js/defaults-800.js';
else if (screen.width <= 1024)
  scriptSrc = 'js/defaults-1024.js';
var script = document.createElement('script');
script.src = scriptSrc;
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);

Perhaps? Dynamic-load them based on screen resolution. Could also use document size, browser size, etc. Though I'm not positive you really want to be doing this. Ideally though you should be dealing with relative metrics (like % or em) in your design and avoid this.

like image 128
Brad Christie Avatar answered Sep 27 '22 15:09

Brad Christie


While I'm unsure on why, you can always import JavaScript files through JS Script.

The following links give some information on this.

  • http://www.kevinleary.net/loadexternal-javascript-jquery-getscript/
  • http://www.stackoverflow.com/questions/1140402/how-to-add-jquery-in-js-file
  • http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

ON a side note - Why are you looking at doing this? Surely you can get the resolution of the screen and then adjust calculations / content based on those variables without the need to change JS files. There are so many different resolutions (mobile devises, multiple monitors, wide screen, projectors etc.). A user can also re-size the browsers effectively making this not worth it.

like image 31
Ryan Ternier Avatar answered Sep 27 '22 15:09

Ryan Ternier