Permission Denied calling javascript function - javascript

I am attempting to make ie7-js work with my wordpress installation. After reading about this library it seems like it is a great solution to making my website more compatible with older versions of IE more specifically IE8. It may seem odd to try and still support an old browser like that but I have noticed that several hundred visitors a month are visiting our site using browsers as old as IE6. A majority of our users are elderly and still using Windows XP. Now on to the problem.
I am running a copy of the Windows XP virtual machine with IE8 from modern.ie I have followed the instructions on the library code page on how to include the file. I am trying to get the Specific IE9.js file to work. When I access the page in IE8 I get the error
permission denied: line 850 character 37
I have tracked it down to the line below:
for (var i = 0, imported; i < styleSheet.imports.length; i++)
from this function:
function getCSSText(styleSheet, path, media, level) {
var cssText = "";
if (!level) {
media = toSimpleMedia(styleSheet.media);
level = 0;
}
if (media === "none") {
styleSheet.disabled = true;
return "";
}
if (media === "all" || media === self.media) {
// IE only allows importing style sheets three levels deep.
// it will crash if you try to access a level below this
try {
var canAcess = !!styleSheet.cssText;
} catch (exe) {}
if (level < 3 && canAcess) {
var hrefs = styleSheet.cssText.match(IMPORTS);
// loop through imported style sheets
for (var i = 0, imported; i < styleSheet.imports.length; i++) {
var imported = styleSheet.imports[i];
var href = styleSheet._href || styleSheet.href;
imported._href = hrefs[i].replace(TRIM_IMPORTS, "");
// call this function recursively to get all imported style sheets
cssText += getCSSText(imported, getPath(href, path), media, level + 1);
}
}
// retrieve inline style or load an external style sheet
cssText += encode(styleSheet.href ? loadStyleSheet(styleSheet, path) : styleSheet.owningElement._cssText);
cssText = parseMedia(cssText, self.media);
}
return cssText;
};
Upon researching to see if anyone else has had the same issue I did find posts regarding it but none had solutions to them. I have been trying to sort this out for a few hours now only to be banging my head against the desk. Does anyone have possible solutions or things to check next? I have tried changing file permissions to 777 but that does not seem to work either.

Older browsers have limitations when working with CORS on client-side.
Not quite a "bug" from his javascript and can not be corrected by the client-side.
The best way is to work with CDNs that have permissions to CORS.
http://schock.net/articles/2013/07/03/hosting-web-fonts-on-a-cdn-youre-going-to-need-some-cors/
http://support.maxcdn.com/howto/use-cdn-with-webfonts/
Yet still can be difficult, so another alternative would be to put all the CSS on a sub domain your (or your own domain).
Read about CORS:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
http://enable-cors.org/

Related

Why does javascript create padding in Google Chrome?

I have written some javascript code that creates a preview in a table. In google chrome, however, the table gets extra padding on the bottom.
Google Chrome:
Internet Explore
I have tried the html tags .
Prints preview text:
var textcontent = document.getElementById('kilo');
textcontent.onkeyup = textcontent.onkeypress = function(){
document.getElementById('showtext').innerHTML = this.value;
}
Prints image:
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
I expect a result without padding on the bottom.
padding is CSS related, or using default value. If you need to have clear(0) paddings/margins you've to set it/them using CSS. JavaScript is not about padding but can write HTML or CSS and create element who obviously will have theirs default values. Browsers have sometimes differents settings like default or padding/margin size slightly differents, so set the needed value(s) will fix most of the problems like differences in each browser, some will require more browser specifics settings in order to set unify and erase those differences who 're oten difference of 1 or 2 px.
See also polyfil for more specifics comportements differences in browsers and lack of some modernest stuffs who exist in others and/or laters updates.
note: it's well known that IE is the worst for developpers, better use Edge who's better (stick more to W3C reccomandations) and forget about IE and version of browser who're not uptodate. Not updateing application browser is a wrong this for the user so do web sites for good and updated browsers is more likely to have a good website(i mean anyone will see the same). Testing is still needed for me but i do Firefox then Chrome and later Edge because the 2 first one more at the avant-garde of tech. and following what W3C reccomand. Teting on one or 2 not up to date could be a plus but i don't think so it's really needed, better is to display(and test) site on mobile device with mobile version browsers who 're far more in use to see and browse websites.(+ a website has to be 'mobile first' in order to get a good indexation at serach engine like Google).

Simulate "visit" for javascript analytics tracker

I am using Piwik/Matomo's tracker to provide my users with custom JS trackers, and provide a curated dashboard of analytics that are tailor made for them. One problem I am facing consistently is verifying if the tracker is installed and working correctly.
I have tried using file_get_contents and/or cURL to fetch the page and check if the tracker exists, but this doesn't always work. So I am trying to instead simulate a visit, and see if the tracker sends me any data when it happens.
Since fget/curl do not trigger javascript, is there an alternative (and lightweight) method to fire the page's javascript and trigger a visit for testing?
Update : I implemented this by using PhantomJS as suggested, with the overall function being something like this. Haven't yet tested this extensively for all my users, is there a more elegant solution? -
checktracker
{
if (data exists & data > 0)
{
return true
}
else if (data exists & data = 0)
{
simulate visit with phantomJS //Relevant to question
check again
if ( still 0 )
{
return false
}
else
{
return true
}
}
else
{
invalid site id
}
}
So you want to automatically check if a specific website has integrated Matomo correctly? I recently wanted to do the same to create a browser extention to quickly debug common errors.
One way would be checking the DOM. The Matomo Tracking Code adds a <script>-Tag to the website, so you can check the existence of it via JavaScript:
function getDomElements() {
var allElements = document.getElementsByTagName('script');
for (var i = 0, n = allElements.length; i < n; i++) {
if (allElements[i].hasAttribute("src") && allElements[i].getAttribute("src").endsWith("piwik.js")) { // TODO: support renamed piwik.js
return allElements[i];
}
}
}
But if you also have access to the JS console, the probably better solution would be checking if the tracking code has initialized correctly:
If something like this outputs your Matomo URL, chances are high that the tracking code is embedded correctly.
var tracker == window.Piwik.getAsyncTracker()
console.log(tracker.getPiwikUrl())
Of course it can still fail (e.g. if the server returns 403 on the piwik.php request, but if you control the server, this shouldn't happen)
To run the check automatically, you could look into Headless Chrome or Firefox.

Automatic Language Selection without click on flag [duplicate]

This question already has answers here:
Get visitors language & country code with javascript (client-side) [duplicate]
(3 answers)
How to determine user's locale within browser?
(10 answers)
Closed 4 years ago.
I have been trying to detect the browser language preference using JavaScript.
If I set the browser language in IE in Tools>Internet Options>General>Languages, how do I read this value using JavaScript?
Same problem for Firefox. I'm not able to detect the setting for tools>options>content>languages using navigator.language.
Using navigator.userLanguage , it detects the setting done thru
Start>ControlPanel>RegionalandLanguageOptions>Regional Options tab.
I have tested with navigator.browserLanguage and navigator.systemLanguage but neither returns the value for the first setting(Tools>InternetOptions>General>Languages)
I found a link which discusses this in detail, but the question remains unanswered :(
I think the main problem here is that the browser settings don't actually affect the navigator.language property that is obtained via javascript.
What they do affect is the HTTP 'Accept-Language' header, but it appears this value is not available through javascript at all. (Probably why #anddoutoi states he can't find a reference for it that doesn't involve server side.)
I have coded a workaround: I've knocked up a google app engine script at http://ajaxhttpheaders.appspot.com that will return you the HTTP request headers via JSONP.
(Note: this is a hack only to be used if you do not have a back end available that can do this for you. In general you should not be making calls to third party hosted javascript files in your pages unless you have a very high level of trust in the host.)
I intend to leave it there in perpetuity so feel free to use it in your code.
Here's some example code (in jQuery) for how you might use it
$.ajax({
url: "http://ajaxhttpheaders.appspot.com",
dataType: 'jsonp',
success: function(headers) {
language = headers['Accept-Language'];
nowDoSomethingWithIt(language);
}
});
Hope someone finds this useful.
Edit: I have written a small jQuery plugin on github that wraps this functionality: https://github.com/dansingerman/jQuery-Browser-Language
Edit 2: As requested here is the code that is running on AppEngine (super trivial really):
class MainPage(webapp.RequestHandler):
def get(self):
headers = self.request.headers
callback = self.request.get('callback')
if callback:
self.response.headers['Content-Type'] = 'application/javascript'
self.response.out.write(callback + "(")
self.response.out.write(headers)
self.response.out.write(")")
else:
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("I need a callback=")
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=False)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Edit3: Have open sourced the app engine code here: https://github.com/dansingerman/app-engine-headers
var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF
window.navigator.userLanguage is IE only and it's the language set in Windows Control Panel - Regional Options and NOT browser language, but you could suppose that a user using a machine with Window Regional settings set to France is probably a French user.
navigator.language is FireFox and all other browser.
Some language code: 'it' = italy, 'en-US' = english US, etc.
As pointed out by rcoup and The WebMacheter in comments below, this workaround won't let you discriminate among English dialects when users are viewing website in browsers other than IE.
window.navigator.language (Chrome/FF/Safari) returns always browser language and not browser's preferred language, but: "it's pretty common for English speakers (gb, au, nz, etc) to have an en-us version of Firefox/Chrome/Safari." Hence window.navigator.language will still return en-US even if the user preferred language is en-GB.
Update of year 2014.
Now there is a way to get Accept-Languages in Firefox and Chrome using navigator.languages (works in Chrome >= 32 and Firefox >= 32)
Also, navigator.language in Firefox these years reflects most preferred language of content, not language of UI. But since this notion is yet to be supported by other browsers, it is not very useful.
So, to get most preferred content language when possible, and use UI language as fallback:
navigator.languages
? navigator.languages[0]
: (navigator.language || navigator.userLanguage)
I came across this piece of code to detect browser's language in Angular Translate module, which you can find the source here. I slightly modified the code by replacing angular.isArray with Array.isArray to make it independent of Angular library.
var getFirstBrowserLanguage = function () {
var nav = window.navigator,
browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],
i,
language;
// support for HTML 5.1 "navigator.languages"
if (Array.isArray(nav.languages)) {
for (i = 0; i < nav.languages.length; i++) {
language = nav.languages[i];
if (language && language.length) {
return language;
}
}
}
// support for other well known properties in browsers
for (i = 0; i < browserLanguagePropertyKeys.length; i++) {
language = nav[browserLanguagePropertyKeys[i]];
if (language && language.length) {
return language;
}
}
return null;
};
console.log(getFirstBrowserLanguage());
let lang = window.navigator.languages ? window.navigator.languages[0] : null;
lang = lang || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage;
let shortLang = lang;
if (shortLang.indexOf('-') !== -1)
shortLang = shortLang.split('-')[0];
if (shortLang.indexOf('_') !== -1)
shortLang = shortLang.split('_')[0];
console.log(lang, shortLang);
I only needed the primary component for my needs, but you can easily just use the full string. Works with latest Chrome, Firefox, Safari and IE10+.
var language = navigator.languages && navigator.languages[0] || // Chrome / Firefox
navigator.language || // All browsers
navigator.userLanguage; // IE <= 10
console.log(language);
https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages
https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language
Try PWA Template https://github.com/StartPolymer/progressive-web-app-template
navigator.userLanguage for IE
window.navigator.language for firefox/opera/safari
I've been using Hamid's answer for a while, but it in cases where the languages array is like ["en", "en-GB", "en-US", "fr-FR", "fr", "en-ZA"] it will return "en", when "en-GB" would be a better match.
My update (below) will return the first long format code e.g. "en-GB", otherwise it will return the first short code e.g. "en", otherwise it will return null.
function getFirstBrowserLanguage() {
var nav = window.navigator,
browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],
i,
language,
len,
shortLanguage = null;
// support for HTML 5.1 "navigator.languages"
if (Array.isArray(nav.languages)) {
for (i = 0; i < nav.languages.length; i++) {
language = nav.languages[i];
len = language.length;
if (!shortLanguage && len) {
shortLanguage = language;
}
if (language && len>2) {
return language;
}
}
}
// support for other well known properties in browsers
for (i = 0; i < browserLanguagePropertyKeys.length; i++) {
language = nav[browserLanguagePropertyKeys[i]];
//skip this loop iteration if property is null/undefined. IE11 fix.
if (language == null) { continue; }
len = language.length;
if (!shortLanguage && len) {
shortLanguage = language;
}
if (language && len > 2) {
return language;
}
}
return shortLanguage;
}
console.log(getFirstBrowserLanguage());
Update: IE11 was erroring when some properties were undefined. Added a check to skip those properties.
I've just come up with this. It combines newer JS destructuring syntax with a few standard operations to retrieve the language and locale.
var [lang, locale] = (
(
(
navigator.userLanguage || navigator.language
).replace(
'-', '_'
)
).toLowerCase()
).split('_');
Hope it helps someone
There is no decent way to get that setting, at least not something browser independent.
But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)
So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info.
Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader
I can't find a single reference that state that it's possible without involving the serverside.
MSDN on:
navigator.browserLanguage
navigator.systemLanguage
navigator.userLanguage
From browserLanguage:
In Microsoft Internet Explorer 4.0 and
earlier, the browserLanguage property
reflects the language of the installed
browser's user interface. For example,
if you install a Japanese version of
Windows Internet Explorer on an
English operating system,
browserLanguage would be ja.
In Internet Explorer 5 and later,
however, the browserLanguage property
reflects the language of the operating
system regardless of the installed
language version of Internet Explorer.
However, if Microsoft Windows 2000
MultiLanguage version is installed,
the browserLanguage property indicates
the language set in the operating
system's current menus and dialogs, as
found in the Regional Options of the
Control Panel. For example, if you
install a Japanese version of Internet
Explorer 5 on an English (United
Kingdom) operating system,
browserLanguage would be en-gb. If you
install Windows 2000 MultiLanguage
version and set the language of the
menus and dialogs to French,
browserLanguage would be fr, even
though you have a Japanese version of
Internet Explorer.
Note This property does not indicate
the language or languages set by the
user in Language Preferences, located
in the Internet Options dialog box.
Furthermore, it looks like browserLanguage is deprecated cause IE8 doesn't list it
I had the same problem, and I wrote the following front-end only library that wraps up the code for multiple browsers. It's not much code, but nice to not have to copy and paste the same code across multiple websites.
Get it: acceptedlanguages.js
Use it:
<script src="acceptedlanguages.js"></script>
<script type="text/javascript">
console.log('Accepted Languages: ' + acceptedlanguages.accepted);
</script>
It always returns an array, ordered by users preference. In Safari & IE the array is always single length. In FF and Chrome it may be more than one language.
I would like to share my code, because it works and it is different than the others given anwers.
In this example, if you speak French (France, Belgium or other French language) you are redirected on the French page, otherwise on the English page, depending on the browser configuration:
<script type="text/javascript">
$(document).ready(function () {
var userLang = navigator.language || navigator.userLanguage;
if (userLang.startsWith("fr")) {
window.location.href = '../fr/index.html';
}
else {
window.location.href = '../en/index.html';
}
});
</script>
If you only need to support certain modern browsers then you can now use:
navigator.languages
which returns an array of the user's language preferences in the order specified by the user.
As of now (Sep 2014) this works on:
Chrome (v37),
Firefox (v32) and
Opera (v24)
But not on:
IE (v11)
Javascript way:
var language = window.navigator.userLanguage || window.navigator.language;//returns value like 'en-us'
If you are using jQuery.i18n plugin, you can use:
jQuery.i18n.browserLang();//returns value like '"en-US"'
If you are developing a Chrome App / Extension use the chrome.i18n API.
chrome.i18n.getAcceptLanguages(function(languages) {
console.log(languages);
// ["en-AU", "en", "en-US"]
});
DanSingerman has a very good solution for this question.
The only reliable source for the language is in the HTTP-request header.
So you need a server-side script to reply the request-header or at least the Accept-Language field back to you.
Here is a very simple Node.js server which should be compatible with DanSingermans jQuery plugin.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(req.headers));
}).listen(80,'0.0.0.0');
For what it's worth, Wikimedia's Universal Language Selector library has hooks for doing this:
https://www.mediawiki.org/wiki/Extension:UniversalLanguageSelector
See the function getFrequentLanguageList in resources/js/ext.uls.init.js . Direct link:
https://gerrit.wikimedia.org/r/gitweb?p=mediawiki/extensions/UniversalLanguageSelector.git;a=blob;f=resources/js/ext.uls.init.js;hb=HEAD
It still depends on the server, or more specifically, the MediaWiki API. The reason I'm showing it is that it may provide a good example of getting all the useful information about the user's language: browser language, Accept-Language, geolocation (with getting country/language info from the CLDR), and of course, user's own site preferences.
Dan Singerman's answer has an issue that the header fetched has to be used right away, due to the asynchronous nature of jQuery's ajax. However, with his google app server, I wrote the following, such that the header is set as part of the initial set up and can be used at later time.
<html>
<head>
<script>
var bLocale='raw'; // can be used at any other place
function processHeaders(headers){
bLocale=headers['Accept-Language'];
comma=bLocale.indexOf(',');
if(comma>0) bLocale=bLocale.substring(0, comma);
}
</script>
<script src="jquery-1.11.0.js"></script>
<script type="application/javascript" src="http://ajaxhttpheaders.appspot.com?callback=processHeaders"></script>
</head>
<body>
<h1 id="bLocale">Should be the browser locale here</h1>
</body>
<script>
$("#bLocale").text(bLocale);
</script>
</html>
If you don't want to rely on an external server and you have one of your own you can use a simple PHP script to achieve the same behavior as #DanSingerman answer.
languageDetector.php:
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
echo json_encode($lang);
?>
And just change this lines from the jQuery script:
url: "languageDetector.php",
dataType: 'json',
success: function(language) {
nowDoSomethingWithIt(language);
}
If you have control of a backend and are using django, a 4 line implementation of Dan's idea is:
def get_browser_lang(request):
if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
return JsonResponse({'response': request.META['HTTP_ACCEPT_LANGUAGE']})
else:
return JsonResponse({'response': settings.DEFAULT_LANG})
then in urls.py:
url(r'^browserlang/$', views.get_browser_lang, name='get_browser_lang'),
and on the front end:
$.get(lg('SERVER') + 'browserlang/', function(data){
var lang_code = data.response.split(',')[0].split(';')[0].split('-')[0];
});
(you have to set DEFAULT_LANG in settings.py of course)
Based on the answer here Accessing the web page's HTTP Headers in JavaScript I built the following script to get the browser language:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
var contentLanguage = headers.match( /^content-language\:(.*)$/gm );
if(contentLanguage[0]) {
return contentLanguage[0].split(":")[1].trim().toUpperCase();
}
If you are using ASP .NET MVC and you want to get the Accepted-Languages header from JavaScript then here is a workaround example that does not involve any asynchronous requests.
In your .cshtml file, store the header securely in a div's data- attribute:
<div data-languages="#Json.Encode(HttpContext.Current.Request.UserLanguages)"></div>
Then your JavaScript code can access the info, e.g. using JQuery:
<script type="text/javascript">
$('[data-languages]').each(function () {
var languages = $(this).data("languages");
for (var i = 0; i < languages.length; i++) {
var regex = /[-;]/;
console.log(languages[i].split(regex)[0]);
}
});
</script>
Of course you can use a similar approach with other server technologies as others have mentioned.
For who are looking for Java Server solution
Here is RestEasy
#GET
#Path("/preference-language")
#Consumes({"application/json", "application/xml"})
#Produces({"application/json", "application/xml"})
public Response getUserLanguagePreference(#Context HttpHeaders headers) {
return Response.status(200)
.entity(headers.getAcceptableLanguages().get(0))
.build();
}
i had a diffrent approach, this might help someone in the future:
the customer wanted a page where you can swap languages.
i needed to format numbers by that setting (not the browser setting / not by any predefined setting)
so i set an initial setting depending on the config settings (i18n)
$clang = $this->Session->read('Config.language');
echo "<script type='text/javascript'>var clang = '$clang'</script>";
later in the script i used a function to determine what numberformating i need
function getLangsettings(){
if(typeof clang === 'undefined') clang = navigator.language;
//console.log(clang);
switch(clang){
case 'de':
case 'de-de':
return {precision : 2, thousand : ".", decimal : ","}
case 'en':
case 'en-gb':
default:
return {precision : 2, thousand : ",", decimal : "."}
}
}
so i used the set language of the page and as a fallback i used the browser settings.
which should be helpfull for testing purposes aswell.
depending on your customers you might not need that settings.
I have a hack that I think uses very little code and is quite reliable.
Put your site's files in a subdirectory. SSL into your server and create symlinks to that subdirectory where your files are stored that indicate your languages.
Something like this:
ln -s /var/www/yourhtml /var/www/en
ln -s /var/www/yourhtml /var/www/sp
ln -s /var/www/yourhtml /var/www/it
Use your web server to read HTTP_ACCEPT_LANGUAGE and redirect to these "different subdirectories" according to the language value it provides.
Now you can use Javascript's window.location.href to get your url and use it in conditionals to reliably identify the preferred language.
url_string = window.location.href;
if (url_string = "http://yoursite.com/it/index.html") {
document.getElementById("page-wrapper").className = "italian";
}

Loading CSS from different domain, and accessing it from Javascript

I want to split up my website acrosss different servers and use subdomains for this purpose.
xttp://site.com will serve the main php file
xttp://static.site.com will serve the css and js
xttp://content.site.com will serve images and such
(xttp to prevent stackoverflow form thinking it is a url)
For the why, read below.
However, I run into a problem when I try to access through javascript any of the css rules. NS_ERROR_DOM_SECURITY_ERR to be precise. This is a relatively recent security measure and has to do with protection against cross domain scripting.
In the past, there were measures to fix this including just turning this protection off. This no longer works.
My question:
Is there anyway to access a normally loaded css rule through javascript if it is from a different domain then the main page?
The javascript:
MUI.getCSSRule=function(selector){
for(var ii=0;ii<document.styleSheets.length;ii++){
var mysheet=document.styleSheets[ii];
var myrules=mysheet.cssRules?mysheet.cssRules:mysheet.rules;
for(i=0;i<myrules.length;i++){
if(myrules[i].selectorText==selector){
return myrules[i]
}
}
}
return false
};
The javascript and css is loaded from the html with absolute paths
and the site url is "http://site.com"
Both domains are fully under my control but they are seperate machines (virtual for now but if it is even possible, in production they might not even be in the same location)
Rephrasing the question:
Is there any way to let Firefox and other browsers know that it should treat certain domains as being the same even though the domain names are different?
Why? So, I can easily use different servers with their own configuration, optimized for their task. A fast machine for the php, a simple one to serve the static stuff, a large machine for the content.
Why? Costs. A static server typically has little need for security against anyone downloading the files. It has little content so no need for an expensive array. Just load it in memory and serve from there. Memory itself can be limitted as well, try it. A PHP server, in my case at least, however will typically need lots of memory, need redundant storage, extensive logging. A content server will need massive storage and massive bandwidth but relatively little in the way of CPU power. Different hardware/hosting requirements for each. Finetuning each not only gives better performance but also reduces hosting costs, for me at least still one of the biggest costs of running a website.
CORS (cross-origin resource sharing) is a standard that allows sites to opt-in to access of resources cross-origin. I do not know if Firefox applies this to CSS yet; I know that it works for XMLHttpRequest, and it is intended that it will work for most other cross-domain request restrictions, but I haven't tested it in your precise use-case.
You can add following header to responses from static.site.com to allow your main page to access the content of resources served from there:
Access-Control-Allow-Origin: http://site.com
Or even, if you don't consider any of your content on static.site.com to be sensitive:
Access-Control-Allow-Origin: *
There's more information available on the Mozilla Developer Network.
I wrote a little function that will solve the loading problem cross-browser including FF. The comments on GitHub help explain usage. Full code at https://github.com/srolfe26/getXDomainCSS.
Disclaimer: The code below is jQuery dependent.
Sometimes, if you're pulling CSS from a place that you can't control the CORS settings you can still get the CSS with a <link> tag, the main issue to be solved then becomes knowing when your called-for CSS has been loaded and ready to use. In older IE, you could have an on_load listener run when the CSS is loaded.
Newer browsers seem to require old-fashioned polling to determine when the file is loaded, and have some cross-browser issues in determining when the load is satisfied. See the code below to catch some of those quirks.
/**
* Retrieves CSS files from a cross-domain source via javascript. Provides a jQuery implemented
* promise object that can be used for callbacks for when the CSS is actually completely loaded.
* The 'onload' function works for IE, while the 'style/cssRules' version works everywhere else
* and accounts for differences per-browser.
*
* #param {String} url The url/uri for the CSS file to request
*
* #returns {Object} A jQuery Deferred object that can be used for
*/
function getXDomainCSS(url) {
var link,
style,
interval,
timeout = 60000, // 1 minute seems like a good timeout
counter = 0, // Used to compare try time against timeout
step = 30, // Amount of wait time on each load check
docStyles = document.styleSheets // local reference
ssCount = docStyles.length, // Initial stylesheet count
promise = $.Deferred();
// IE 8 & 9 it is best to use 'onload'. style[0].sheet.cssRules has problems.
if (navigator.appVersion.indexOf("MSIE") != -1) {
link = document.createElement('link');
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
link.onload = function () {
promise.resolve();
}
document.getElementsByTagName('head')[0].appendChild(link);
}
// Support for FF, Chrome, Safari, and Opera
else {
style = $('<style>')
.text('#import "' + url + '"')
.attr({
// Adding this attribute allows the file to still be identified as an external
// resource in developer tools.
'data-uri': url
})
.appendTo('body');
// This setInterval will detect when style rules for our stylesheet have loaded.
interval = setInterval(function() {
try {
// This will fail in Firefox (and kick us to the catch statement) if there are no
// style rules.
style[0].sheet.cssRules;
// The above statement will succeed in Chrome even if the file isn't loaded yet
// but Chrome won't increment the styleSheet length until the file is loaded.
if(ssCount === docStyles.length) {
throw(url + ' not loaded yet');
}
else {
var loaded = false,
href,
n;
// If there are multiple files being loaded at once, we need to make sure that
// the new file is this file
for (n = docStyles.length - 1; n >= 0; n--) {
href = docStyles[n].cssRules[0].href;
if (typeof href != 'undefined' && href === url) {
// If there is an HTTP error there is no way to consistently
// know it and handle it. The file is considered 'loaded', but
// the console should will the HTTP error.
loaded = true;
break;
}
}
if (loaded === false) {
throw(url + ' not loaded yet');
}
}
// If an error wasn't thrown by this point in execution, the stylesheet is loaded, proceed.
promise.resolve();
clearInterval(interval);
} catch (e) {
counter += step;
if (counter > timeout) {
// Time out so that the interval doesn't run indefinitely.
clearInterval(interval);
promise.reject();
}
}
}, step);
}
return promise;
}
document.domain = "site.com";
Add to a JS file that is loaded before your CSS file. I would also add the HTTP headers suggested above.

Checking JRE version inside browser

Basically, I'm wanting to figure out the best way to check the user's JRE version on a web page. I have a link to a JNLP file that I only want to display if the user's JRE version is 1.6 or greater. I've been playing around with the deployJava JavaScript code (http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html) and have gotten it to work in every browser but Safari (by using deployJava.versionCheck). For whatever reason, Safari doesn't give the most updated JRE version number - I found this out by displaying the value of the getJREs() function. I have 1.6.0_20 installed, which is displayed in every other browser, but Safari keeps saying that only 1.5.0 is currently installed.
I've also tried using the createWebStartLaunchButtonEx() function and specifying '1.6.0' as the minimum version, but when I click the button nothing happens (in any browser).
Any suggestions?
FYI: Here's my code --
if (deployJava.versionCheck('1.6+')) {
var dir = location.href.substring(0,location.href.lastIndexOf('/')+1);
var url = dir + "tmaj.jnlp";
deployJava.createWebStartLaunchButton(url, '1.6.0');
} else {
var noticeText = document.createTextNode("In order to use TMAJ, you must visit the following link to download the latest version of Java:");
document.getElementById('jreNotice').appendChild(noticeText);
var link = document.createElement('a');
link.setAttribute('href', 'http://www.java.com/en/download/index.jsp');
var linkText = document.createTextNode("Download Latest Version of Java");
link.appendChild(linkText);
document.getElementById('jreDownloadLink').appendChild(link);
}
Probably the best bet would be to check the navigator.plugins array.
Here is a quick example that works in Chrome/Firefox. As far as I know, Internet Explorer does not provide access to the plugins array.
function getJavaVersion() {
var j, matches;
for (j = 0;j < navigator.plugins.length;j += 1) {
matches = navigator.plugins[j].description.match(/Java [^\d]+(\d+\.?\d*\.?\d*_?\d*)/i);
if (matches !== null) {
return matches[1];
}
}
return null;
};
console.log(getJavaVersion()); // => 1.6.0_16
Not sure if it helps you but you can specify the minimum jre version as a clause in the jnlp file. Webstart will not launch your app if the requirement is not met.
See the tag.
Also, have a look at
How to check JRE version prior to launch?

Categories