execute javascript when printing page - javascript

when printing a page, the javascript code seems to be executed.
how can I determine, if the page is currently being printed? I do some js-resizing, and have to handle printing a little bit different.

You can't, except for IE browsers. No other browser has a before print event. You can, however, target a specific stylesheet to only apply while printing:
<!-- In head -->
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
This stylesheet will be applied before printing. This allows you to perform some amazing changes, including hiding major sections, moving items around, and performing print-only styling, such as page breaks.
Another option is to provide the user with a "Print this Page" button. That button can handle your JavaScript, call window.print(), and revert the changes:
function printMe() {
// perform changes
window.print();
// revert changes
}
The window.print() method always blocks (in every browser I've tested), so it's safe to immediately revert the changes afterward. However, if the user choose to print via the menu or toolbar, you are out of luck.
One way I handled that case in a complex web-app was to have a print stylesheet that hid everything but a special DIV. If the user clicked print, they would get a warning message. If they clicked the print button, then that div would be populated with the correct information. It's not great, but at least they didn't get several pages of garbage.

AFAIK there is no general possibility. IE has onbeforeprint and onafterprint which are now added also to Firefox 5/6+ (I dont know for sure). Consider using print specific stylesheets
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
Other relevant questions
onbeforeprint() and onafterprint() equivalent for non IE browsers (PHP, MySQL, JavaScript, HTML)
Trigger resize event on print
What event is fired when window.print() is called?

Related

Programmatically added Stylesheet Element not being honored by dom

In our web app, I'm trying to hit our server to determine if they have made any custom CSS tweaks to the layout of the web app. Upon getting a boolean flag of this, I'm returning the CSS from the server and injecting a new head link after the last one...
The problem is, this isn't updating the page's style or layout. If I go into the sources of the page elements and click on that CSS document in the dev console, I can force it to "notice" that this css is available by simply changing the value of a style reference.
This is the jquery I'm using to inject the CSS:
$("head link[rel='stylesheet']").last().after("<link rel='stylesheet' href='4DACTION/WEB_Mobile_CustomCSS' type='text/css' media='screen'>");
Any idea why it wouldn't force the page to use it until I've made a change to it in the debugger?
I used Bootstrap to create an example doing exactly what you described using your code in a setTimeout callback:
setTimeout(function () {
$("head link[rel='stylesheet']").last().after("<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css' type='text/css' media='screen'>");
}, 1000);
check it out: http://jsfiddle.net/v089p29a/ it switches from flat buttons to 3D ones.
I'm not sure why this is not working for you. Maybe your URL is not valid like adeneo suggested. Also be sure to put your code in the $(window).load() or $(document).ready() event handlers to ensure that the DOM is ready to be manipulated.

What do printers ignore?

When printing an HTML document the bgcolor of a table cell is ignored.
What else is ignored when one tries to print documents?
I'm trying to make a particular website look a certain way when printed out but am having some difficulty doing so not knowing what attributes printers use and which ones they ignore.
Thanks!
The link you're referring to is about browser-specific print handling. Check out the each supported browser's printing properties for more info there.
Regularly, though, WYSIWYG when it comes to printing an HTML page.
You could specify a specific CSS file for printing by adding the following tag to your <head> tag:
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
Where print.css is the path to your CSS file.
Addition:
Though you can't override the Browser-preferences, there's nothing you can do to print your BG in non-allowing browsers. Check the printing preferences for those options.
My best idea is to export your web-page to PDF and print that. See web2pdfconvert, for example of such a service. You could also install a plugin on your server side that does exactly the same thing, and the send it your HTML via AJAX.
Another Addition: Take a look at jsPDF which is completely client side and thus simpler. You can use it to convert the page to pdf and than print it as it is.
Things that may be ignored are completely dependent upon the browser in question and the print settings for that browser.
For example, in Chrome you can turn off headers/footers and backgrounds. In Firefox you have control over backgrounds. In IE you have some refined control over frames, linked documents and optionally printing a table of links.
Your best bet is to simply provide a style sheet for media="print" and define how you want the page to look.

Dynamically and asynchronously loading CSS (by setting the "href" attribute in Javascript)

On our site we load stylesheets dynamically based on whether the display is retina or not. Right now, we are using document.write for each <link href="stylesheet.css"> we insert in the page, with different css files if the display is retina.
However, this hurts performance because it causes the css files to load synchronously, as the browser has no way of parsing the javascript to load the next file before the previous one is finished. I believe we can reduce page load time if we take advantage of modern browsers' capability to look ahead and fetch resources asynchronously - in another words, if we load the CSS files in parallel instead.
My current solution is to create a <link id="link-tag-id" href=""> tag for every stylesheet to be loaded, immediately followed by a script which determines the retina status, then fills in the quotations with the appropriate file, along the lines of:
document.getElementById("link-tag-id").setAttribute("href", "retina-stylesheet.css")
This seems to work fine, and when I examine the network waterfalls in Chrome developer tools, as well as on WebPageTest.org (running Chrome, Firefox, and IE), the stylesheets indeed load in parallel. However, it seems a little hacky. I was wondering if there are any dangers to creating a <link> tag with an empty href attribute, and if so, what are they?
On a broader note, are there any other recommendations on how to load CSS dynamically and asynchronously?
Thanks for your help!
EDIT: I just discovered this works too:
document.getElementById("link-tag-id").href = "retina-stylesheet.css"
You could use media queries inside your stylesheet to determine if the display is a retina display, then load in the required CSS.
http://css-tricks.com/snippets/css/retina-display-media-query/
http://mobile.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/

Why do we use <script> for scripts, but not <style> for external CSS?

A relative of mine who started to learn Web Development asked me this question.
Why <script src="min.js"></script> and <link rel="stylesheet" href="min.css">? Why not <style href="min.css"></style>. Why do we use link tag to add external CSS in the page but when we link CSS to page but we use <style>...</style> when we write CSS inside <head>?
I told him that it's because of spec. Is there any more info to give to him?
It's historical... coincidence? You can recommend him reading part about Past of diveintohtml5.info, where there are some interesting stories, actually mail correspondences, between web developers. Web developers means they were, in fact, developing the Web we see nowadays ;)
I.e. <img> tag we are used to:
<IMG SRC="file://foobar.com/foo/bar/blargh.xbm">
could be:
<ICON name="NoEntry" href="http://note/foo/bar/NoEntry.xbm">
or
<A HREF="..." INCLUDE>See photo</A>
or
<INCLUDE HREF="...">
but finally devs decided to stick with <img>, which was already implemented:
We’re not prepared to support INCLUDE/EMBED at this point. … So we’re
probably going to go with (not ICON, since not all
inlined images can be meaningfully called icons). For the time being,
inlined images won’t be explicitly content-type’d; down the road, we
plan to support that (along with the general adaptation of MIME).
Actually, the image reading routines we’re currently using figure out
the image format on the fly, so the filename extension won’t even be
significant.
I don't know direct answer to your question, but I'm pretty curious about <link> tag, too. Finding answer would probably include some web archives digging.
There is a difference, at least from the W3C's point of view.
A <style> element introduces a block of CSS rules that apply to the current document. However, external style sheets are actually considered as whole documents related to the current page, and user agents are free to ignore such documents, depending on the type and media attributes of the link. For instance:
<link rel="stylesheet" type="text/css" media="screen" href="screen.css" />
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
In this situation, user agents would typically only follow one of the links, either the screen one (for normal rendering) or the print one (for, well, printing). The idea was to preserve bandwidth by only downloading the appropriate resource, instead of fetching everything and filtering on the media type later.
This is mentioned in the specification:
When the LINK element links an external style sheet to a document, the
type attribute specifies the style sheet language and the media
attribute specifies the intended rendering medium or media. User
agents may save time by retrieving from the network only those style
sheets that apply to the current device.
They both have a basically identical meaning, and you have spotted a sort of inconsistency in HTML. The cause of this is that the standards were based on the implementations of different browsers. Different browsers came up with the attributes in the different tags, and the W3C just decided to keep some of the inconsistencies in order to maintain backwards compatability.
Elements that use src: script img iframe input video frame
Elements that use href: a link base
This might explain things, I guess: http://www.w3.org/TR/html4/struct/links.html
The <link> tag is used to "link" other documents to the current one, and describe it's relationship, or rel, with it.
You can also use <link> to link other things to the document. For example, favicons:
<link rel="shortcut icon" href="favicon.ico" />
Possible reason for link ref vs style:
link can only go on the head, where "Metadata content" is allowed, typically head,
style could not go in the body before HTML5 (now you can with scoped, but still not to external styles). Therefore, the choice between link ref and style src is arbitrary.
script, however, could already include an external script in the body before HTML5, so there had to be script src. But since it had to exist, why not allow it in the head as well (where script was already allowed), and disallow link rel=script to avoid duplication?
Apparently Tim Berners-Lee wanted everything to be done with <a: https://youtu.be/3QEoJRjxnxQ?t=901 !

How do I show content when Javascript isn't available, hide it when javascript is available and not flicker in either case?

I have a simple form for shipping options and I am using javascript to auto submit the form when someone selects a new option from the drop down list.
In order to support browsers without javascript there is also a button to submit the form. This button is hidden using javascript.
However, this means my button is visible for a brief period of time and can cause a flicker as the rest of the content is reformatted.
Can anyone suggest a way of creating the button so it starts off hidden, but is made visible only if javascript is not available? eg, start out with display:none; and magically change to display:block; if and only if there is no javascript.
Just put anything inside <noscript> ... </noscript> tags and then it will only appear if JavaScript is not enabled/available.
It depends on how you are hiding it, are you using a DOM ready or a window ready? Window ready waits for all images to download, which is generally far too long.
For accessibility, reasons, I'd hide it on DOM loaded. But to ensure it won't show up, you could put it in a noscript element
<noscript>
<input type="submit" />
</noscript>
As for your last paragraph, nothing like that can happen in the absence of JavaScript.
Just write unobtrusive javascript: http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/.
What you do is write your page as a normal page, but, then use the code at the bottom to start the javascript, and start editing the page to make it more interactive. The beauty of this is that if they have javascript turned off the page is normal, but, if they have it on, then you can gracefully add more features.
I am not a big fan of the option as that may mean lots of extra code to be downloaded that isn't needed.
On this page look at comment 5 for a good solution to be able to make changes before anything is actually displayed:
http://dean.edwards.name/weblog/2006/06/again/
You could use script before and after the submit button to write hidden div element start and end tags.
One option would be to start with your button shown, and then modify its CSS from JavaScript:
<head>
...
<link rel="stylesheet" href="style.css" type="text/css" charset="utf-8">
<script>
document.styleSheets[0].addRule(".hideMe", "display:none");
</script>
...
</head>
Modifying the stylesheet instead of the button (and putting this code outside of an onload) ensures that it'll be hidden before the button is drawn.

Categories

Resources