I cannot find a way to identify whether the CSS, which was created dynamically via creating a <link> tag and then specifying the href attribute had indeed loaded.
Consider the following example:
var css = document.createElement("link");
css.href = "not-a-directory/not-a-css";
document.body.appendChild(css);
Some browsers (Firefox), will dispatch "onload" event even if the path doesn't designate an existing file, however, this would only happen if sandbox policies would have not been violated, if file existed. Opera, Google Chrome and Safari - all report the problem in some way, but I can't find a way to handle that in JavaScript.
I'm not interested in supporting MS Internet Explorer (the project will be deployed to embedded WebKit / Opera browsers), but if there is a crossplatform way - that's, of course, welcomed.
PS. "onerror" doesn't seem to trigger in any browser.
CLARIFICATION
Sorry, I had to provide more info. Now I'll try to fix that:
I prefer not to use other libraries (like jQuery), but if they solved it somehow, that's a valid solution, if I can take a look at how they did it.
The code will be deployed to either Opera or WebKit browsers on SmartTV (read it as severe size limitations + files may be required to load from file-system rather than from the net). This is why I can't use XMLHttpRequest.
If you can think of a way to test whether the text file exists given the path (think iframe, link - perhaps other elements?) That is a good option too.
Finally, after much struggle, here's what I did (but alternative solutions are welcome!):
Created a class with the name which is unlikely to happen in other CSS files, say:
.x29048723049820394 { color: #514159 }
and then created a div tag in the HTML page, where I wanted to test whether the CSS has indeed loaded. After creating a link tag (don't forget - you also need to specify the rel attribute, otherwise the style won't load), I set timer to wait for the div I just created to change color. After the color changed I'd assume that the CSS had loaded. Or if the time ran out, I'd give up, assuming that the CSS didn't load.
On the way I also discovered, that in case the CSS file is loaded from the file system, even the same directory as the original HTML, which requests it, you will run into security-related errors when either trying to access the innerHTML of the link or when trying to iterate through the style sheets of the document.
If you know a specific class name that should be loaded then you could use javascript to loop through all the style sheets and class names to see if it was loaded.
It is my understanding that there's no elegant and reliable way of detecting it, everything is more or less hacks.
Here's my hack off the top of my head:
$.ajax({
url: "/style.css",
dataType: "text",
success: function (cssString) {
// css file exists, and was loaded correctly.
$("head").append($("<style/>").text(cssString));
},
error: function (e) {
// css file did not exist, we can check status code with e.status (404 etc)
}
});
We basically load the css file as text using ajax and then attach the loaded data to the dom. This way we can reliably detect failures, but other than that it's a total hack. You most likely get a flash of unstyled content. I'm not sure I would use it, but I thought it might be fun to throw it out there along with all other hacks :-)
Related
I have red other answers however none of them cover my case.
I have a page (http://www.lacertussoftware.com/) and there is some javascript in one of my included files that is setting the min height and height of my page on the body tag. How can i figure out what javascript is doing this? I have 7 or so files that if i remove my parallax effect / nice scrolling / the gap all go away and don't know what is doing it. Breakpointing is not useful as its on page load (especially because the code i have included on the page is not minified.)
Have you considered simply searching the sources for /min-height/ or /body.{0,50}min-height/ (and the CSSOM equivalent minHeight)?
Alternatively you can add a getter/setters for the style property to the HTMLElement/Element prototype which logs accesses to the style property and then forwards calls them to the native browser implementation. If that doesn't work you may also have to instrument .setAttribute() since the style property can be modified that way too.
Obviously this has to be done as early as possible in the document.
You could also try chrome's "break on attributes modification" feature in the the elements view of the dev tools. Or the DOMEvent breakpoints under sources.
You could try inserting a debugger; statement as a first thing in the dom ready handler, all js will pause.
Now right click on the element in the source and add a break on -> attributes modifications
I have a situation where I am loading external HTML into a WYSIWYG editor on a web page. The external HTML is from a trusted source, and includes what ever is between two specific <div> tags from a number of different pages.
My problem is that some of the pages contain inline javascript event handlers. So when I am working in the WYSIWYG editor, certain events cause the execution of this js.
Mostly it doesn't do anything other than fill up the console with errors saying ... is not defined, and this may be all it is, and that wouldn't be a problem. But still, it's messy, and I don't know if there isn't a page somewhere that might execute something like alert(...) which could get extremely annoying. The code is all trusted, but detached from its intended context, it could produced undesirable results.
I want to find a way to globally prevent this execution, preferably without modifying the inline script. I could do something like attach =false; to each handler, but then I have to check all the incoming elements, and even with regular expressions, this will degrade performance. Also, I then would have to remove it before submitting the edited HTML back to the server, which seems like a major pain, and difficult to do flawlessly.
Is there a way to prevent this online code from being executed within this particular context?
Depending on what browser you are trying to support, you can checkout 'Content Security Policy' headers. Checkout http://caniuse.com/contentsecuritypolicy for details on browser support.
If you target browser is in the list, CSP can do exactly what you are looking for. It will disable event handlers by default. It will block execution of any code embedded within on the page in addition to blocking event handlers. So you will need to move all your js code, if present on the html page to a separate js, specify that filename in the safe-list and load your js from there.
CSP are set as Http headers but with the new specification it can be set using meta tags as well. Checkout https://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#html-meta-element--experimental.
For WebKit supported browsers(Chrome/Safari) something like
would restrict load from any external source. You can add a list of accepted sources to the list and explore what works for you.
For firefox, though its there in the specification, I do not think the meta tag is supported yet.
https://developer.mozilla.org/en-US/docs/Security/CSP/Introducing_Content_Security_Policy.
So to summarize, as long as you can set headers for the Web-Server that is hosting the web page (unless you only want Chrome/Safari support), and your target browser supports CSP, you might give it a shot.
I copied this from sitepoint forum, a question similar to yours. This takes an approach of pulling div out of the parent and putting it back on. If this is what you want here is the example code:
var div = document.getElementById('div');
var nextSibling = div.nextSibling;
var parent = div.parentNode;
parent.removeChild(div);
function reCreateElement() {
if (nextSibling) {
parent.insertBefore(div, nextSibling);
} else {
parent.appendChild(div);
}
}
setTimeout(reCreateElement, 100);
// Below is the stuff we don't want to run!
document.getElementById('div').onclick = function() {
alert('CLICKED!');
}
I've written a small HTML5 page that I need to be able to support multiple languages. I've implemented the language control by making the page load a JSON file into memory (in the HEAD) and then running a jQuery command to change the text of any element as required.
Everything works fine except that as the change is being called post render (if the document ready function) there is a slight flash as the language gets changed.
Is there an event that is called before the page is rendered but after the DOM is available? If not, are there any suggestions to change implementation.
Cheers..
UPDATE
I've found a few answers to this on other sites. The general consensus appears to be that this isn't possible as most browsers render as they parse. The workaround that is suggested is to hide (display:'none') the body in script and then show it (display:'') after the updates in the document ready function. It sort of works for me although isn't 100% perfect.
Sounds like you are having an issue with FOUC (Flash Of Unstyled Content)
There are a few ways to get around it. You could add this to your body:
<body class="fouc">
And then have this CSS:
.fouc{display:none;}
And finally this script:
$(function(){
$('.fouc').show();
});
This works by initially hiding the page, and then once you are ready, turning it on with javascript. You may need to ensure your manipulation occurs ahead of the $('.fouc').show(); call.
One effective solution, though not the one you are probably looking for, is to use OUTPUT BUFFERING ... What is output buffering?
I've created a page with CSS. Now I must change from my editor to my browser and refresh the full page, just to have a look at every little change. But I don't want to refresh the page, because I have some animations.
So is there anything which I can use that my site updates automatically after a CSS update?
Maybe with JavaScript, jQuery, Ajax or something?
Here you are: http://cssrefresh.frebsite.nl/
CSSrefresh is a small, unobstructive javascript file that monitors the CSS-files included in your webpage. As soon as you save a CSS-file, the changes are directly implemented, without having to refresh your browser.
Just insert the javascript file and it works!
But note: It only works when you have the files on a server!
Edit: LiveStyle
If you develop with Sublime Text and Google Chrome or Apple Safari, then you should use Emmet LiveStyle. This is a more powerful Live CSS-Reloader.
Now I use it instead of CSS Refresh.
If you want more information about this awesome plugin, please read the Post by Smashing Magazine
With jQuery you can create a function that reloads external stylesheets.
/**
* Forces a reload of all stylesheets by appending a unique query string
* to each stylesheet URL.
*/
function reloadStylesheets() {
var queryString = '?reload=' + new Date().getTime();
$('link[rel="stylesheet"]').each(function () {
this.href = this.href.replace(/\?.*|$/, queryString);
});
}
Have a look at http://livereload.com/.
It works as a browser plugin for OS X and windows. I like it because I do not have to embed additional javascript which I could accidentally commit in my versioning control.
I find browser plugins/extensions to be the easiest solution. They don't require any code changes to your individual sites. And they can be used for any site on the web — which is useful if I modify something in-memory real quick to hide a toolbar or fix a bug temporarily; once finished mucking with it, I can press a key and all the CSS is back to normal.
Once installed, (most) CSS reloaded plugins/extensions don't reload the CSS automatically. But usually work with something as simple as a toolbar button, a context menu item, and/or a simple key press to reload the CSS. I find this method is less error prone anyway, and is much less complicated then some of the automated solutions out there.
Some examples (feel free to suggest some others):
Chrome:
tin.cr (includes automatic reload, and can persist in-browser changes to source files)
CSS Refresh
Firefox:
CSS Reloaded
CSS Refresh
Here is my little Project. Please give it a try
CSS Auto reload on Github
Yes you can manipulate the CSS via jQuery:
$(".classToBeReplaced").switchClass( "classToBeReplaced", "newClass", 1000 );
You could also use the toggleClass method.
http://api.jquery.com/toggleClass/
http://jqueryui.com/demos/switchClass/
Firebug for FireFox.
It's a plugin in an attached/separate window. Changes to HTML/CSS appear instantly, elements are highlighted.
Advantage over JS hacks is that you can't copy this accidentally to your production instance.
You are looking for Live Reload:
It's available as a browser extension and easy to implement
http://livereload.com/
The new open-source code editor, brackets, has a Live Development feature where you can edit CSS in the editor and it will immediately be reflected in the chrome browser. It currently only works for CSS editing, but HTML editing is coming soon!
Firebug for Firefox is my prefered method:
https://addons.mozilla.org/de/firefox/addon/firebug/
You can edit HTML and CSS on the fly, quickly deactivate CSS rules (without deleting them), add or remove HTML and so on. If you wan't to tweak your design this is your choice. You can even save changes to a local copy, but I hardly ever use that feature.
If you are using Firefox then you can install Web Developer Toolbar 1.2.2 from Add-on of Firefox which has option of Reload Linked Stylesheets.
Try using CSS Brush, a chrome plugin for creating CSS live. You needn't have to write all CSS in a text editor, come back to browser and reload it, rather write the CSS live as if you were doing it in a text editor. You will have more features than a text editor here like context-sensitive-menu, use duplicate properties, select complete CSS path or a filtered path of a element directly from the page.
This might help -> chaicode
Its a live CSS, Javascript and HTML editor that is opensource and a wip.
github
I normally work with jQuery, which takes away most of the cross browser pain (although not, unfortunately, all). However, it doesn't seem to have any support for manipulation of the CSS DOM, and this still seems to be a bit of a minefield - QuirksMode has some information.
Our application allows users to theme their site to some extend by generating a CSS stylesheet with the colours that they have selected. It's pretty straightforward, but I'd like to let them "preview" it by applying the changes directly to the CSS DOM, before having them save it back to the database and generating the CSS file.
Does anyone know of a library which will make cross browser CSS DOM maniuplation easier? Just so we're clear, I'm not trying to change the css rules on an element, or set of elements (like with $.css()), or to add/remove classes. I would like to modify the stylesheets directly.
I highly recommend the YUI stylesheet utility. I haven't seen any other libraries with as much functionality or as clean an interface.
Couldn't you just add or replace a <style> element in the main document's DOM, and fill it with the generated CSS?
Best and easiest way, is to create a .jsp .php or whatever you're using which accepts colour parameters, which in turn renders a .css output with colours replaced.
Use JavaScript to make a request with colour parameters and append the css script to the page.
It is possible to do it directly on the styleSheet object, though this will take more time and create more maintenance. Everytime you want to change your custom stylesheet you actually use for production, you will also have to change the preview version. Ergo discrepancies will ensue.
Just reuse the stylesheet template you're going to use for production anyways.
Maybe you should try something like:
document.styleSheets[0].disabled = true;
This disabled the first stylesheet of the current page. Maybe if you play around with it you can resolve your problem.