简体   繁体   中英

Why does WinJS Navigation app apply css to any visited page?

I develop WinJS Navigation app (Windows 8.1/WP 8.1) and there's one problem: I've linked .css file to only one .html file, but when I go to any other .html page and if it has any same class then app applies .css from first page I went !

  • I don't link that .css to host (default.html).
  • It's not depending on which Visual Studio I use.
  • I have same bug in WinJS 2.0, 3.0 and 4.4.0.

There's a question: why does WinJS do this? Is there any solution or workaround?

You can reproduce my problem on your VS2013 or VS2015: zip (debug Windows project, not WindowsPhone).

When using WinJS navigation and page controls, the "navigations" are happening with DOM replacement inside the single context of default.html or whatever your root app page is, and not by dumping default.html (and all the CSS/JS that's been loaded) and initialized a new page context.

This single-page navigation model provides several benefits: it preserves the global JavaScript context and allows you to do animations/transitions to move elements on and off the page. If you truly navigate to a new page altogether, you'd reset the JS context and would always navigate through a blank page.

The side-effect, as you're seeing, is that any and all CSS that gets loaded in the course of page navigations is cumulative. That is, a "navigation" in WinJS does not reset any contexts, including CSS, and this can be tricky to manage. There are several ways around this:

  1. Use a global CSS file and avoid using page-specific CSS unless you know something is unique to a page.
  2. Make sure each page has a top-level div with a page-name class like <div class="page1"> and then scope all styles for that page in your CSS using .page1 selectors.
  3. Specifically load and unload CSS files by modifying <link> tags in the page header. This is really the only way to unload CSS, but also means reloading and reparsing the CSS files which will cause a page to re-render.

Generally speaking, I think option 2 is best and most portable.

For a longer writeup, see the section "Page-Specific Styling" in Chapter 3 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition , and I've written up similar material on my blog, http://www.kraigbrockschmidt.com/2013/05/02/css-loading-behaviors-winjs-page-controls/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM