I you have a highly interactive event driven page in rails 5.0.0.1 with Turbolinks.
Having different interactions on different pages, events like window.resize will trigger on pages where I don't really need it.
Is it worth to sacrifice navigation time by disabling Turbolinks to serve page specific javascript, or should I not care and just use if statement in Jquery to check if certain elements are present in the page using their ID.
What is the rails way of doing this?
It is not recommended to serve page specific assets such as javascript. This slows down the user experience since navigating to a new page triggers another asset download.
The whole point of the Rails Asset Pipeline is to gather your assets, minify them and concatenate them all into a single file that the browser downloads only once, the first time a user navigates to your page.
Yes, use jQuery to check if certain elements exist to run some behavior.
The way I've found useful is to not think about js behaviors as page specific but rather, widget specific. e.g. if there's a sortable table in the DOM then initialize the sortable table widget i.e. $(".sortable").sortable()
The above example uses the jQuery plugins pattern. Place your behavior/widget logic inside the jQuery plugin and it will only run when the selector finds elements e.g. $("#nonexistant").something(), something() will not be called. $("#definitelyExists").somethingElse(), somethingElse() will be called.
In the preceding examples, when an element is found and the function is called, the this of the function references the matched elements and you can run your behavior logic on them.
Related
I'm coding in MeteorJS
I'm using a bootstrap based theme.
The dropdowns etc based on bootstrap, driven by plugin javascript code, don't work. Javascript code I write separately (to handle a login button, for example) does work.
There are no errors generated in the console at any time.
Any idea on the potential issues/how to debug this?
The most commom issue by FAR is the unique way that Meteor renders pages.
A normal theme is created with a traditional load order in mind:
a browser goes to a page and starts to parse the HTML from TOP to BOTTOM
As it goes from top to bottom it builds the DOM nodes of the page.
The browser loads the scripts tags that are down at the very bottom of the page, after most of the HTML code.
99.9% of the time these scripts at the bottom of the page require certain DOM nodes to be in existence for them to work. In the traditional top-down approach, this isn't a problem because all the relevant HTML is above these script tags.
Meteor does not have a top-down approach. If anything, it inserts sections of HTML into the page at different times, which means if you are coding in a top-down way, it's highly likely that at least some of your theme's script files get loaded before the HTML that they need to run are rendered on the page.
Your example of a login button event handling is a perfect example.
You first need the browser to parse
<button id="login-button"></button>
into a DOM node so that your accompanying event handler can work:
$('#login-button').click(function(){ //do something});
What that code is doing is first looking for something with #login-button, then attaching a click event listener to it. If #login-button doesn't exist by the time it runs, it has nothing to attach the listener to, and therefore your event handler won't run when the button is eventually clicked.
Imagine that there's a button on one web page (not mine) and when it's clicked it performs some
Javascript. I want to have a button on my web page that performs exactly the same. So I need to
attach all necessary js files (but first I have to find them) to my html page and sometimes add some js to my html page.
What I usually do in this case? I inspect this button html element to see if there's onclick attribute for this button. If it is, I see the function called when button is clicked and then I try to search for this function in current html page and all js files attached to page. Also I need to find all dependencies (like jQuery, fancybox etc.).
If the button doesn't have onclick attribute I have to look for direct getElementById or jQuery selector pointing to this button with rest of code there. Sometimes there's no such a selector and I have to find a nested selector - really hard and annoying thing.
Is there any better, automated way for doing things above. Ideally after selecting the element in DOM (button in this case) and pressing some magic button I will be able to see all js files involved in processing this click and also js code in html page.
It's going to involve digging no matter what you do. But Chrome's Dev Tools can help with the attached event handlers, to an extent. When you right-click an element and inspect it, on the right-hand side there's a panel showing various tabs: [Styles] [Computed] [Event Listeners] [DOM Breakpoints] [Properties]. The [Event Listeners] one shows the listeners directly attached to that element. Of course, on a site using jQuery (which is more than half the sites using JavaScript at all), looking at the handler will dump you into the jQuery event handling code, but it's a start.
Just as a side point: While it's fine to look at the source of pages for inspiration, or to see how they solved a particular problem, or what plugins they're using to get an effect, etc., I assume you're not grabbing large sections of their actual code (as opposed to libraries and plugins with liberal licenses) without their permission, which is probably not cool.
I'm making a game using JavaScript, currently I'm using window.location = "somepage.html" to perform navigation but I'm not sure if that is the correct way to do it. As I said in the title I've choosed Blank App Template so I do not have any navigator.js or something like.
Can you guys tell me the best way to do it?
Although you can use window.location to perform navigation, I'm sure you've already noticed a few of the downsides:
The transition between pages goes through a black screen, which is an artifact of how the underlying HTML rendering engine works.
You lose your script context between pages, e.g. you don't have any shared variables or namespaces, unless you use HTML5 session storage (or WinRT app data).
It's hard to wire up back buttons, e.g. you have to make sure each destination page knows what page navigated to it, and then maintain a back stack in session storage.
It's for these reasons that WinJS + navigator.js created a way to do "pages" via DOM replacement, which is the same strategy used by "single page web apps." That is, you have a div in default.html within which you load an unload DOM fragments to give the appearance of page navigation, while you don't actually ever leave the original script context of default.html. As a result, all of your in-memory variables persist across all page navigations.
The mechanics work like this: WinJS.Navigation provides an API to manage navigation and a backstack. By itself, however, all it really does is manage a backstack array and fire navigation-related events. To do the DOM replacement, something has to be listening to those events.
Those listeners are what navigator.js implements, so that's a piece of code that you can pull into any project for this purpose. Navigator.js also implements a custom control called the PageControlNavigator (usually Application.PageControlNavigator) is what implements the listeners.
That leave the mechanics of how you define your "pages." This is what the WinJS.UI.Pages API is for, and navigator.js assumes that you've defined your pages in this way. (Technically speaking, you can define your own page mechanisms for this, perhaps using the low-level WinJS.UI.Fragments API or even implementing your own from scratch. But WinJS.UI.Pages came about because everyone who approached this problem basically came up with the same solution, so the WinJS team provided one implementation that everyone can use.)
Put together then:
You define each page as an instance of WinJS.UI.Pages.PageControl, where each page is identified by its HTML file (which can load its own JS and CSS files). The JS file contains implementations of a page's methods like ready, in which you can do initialization work. You can then build out any other object structure you want.
In default.html, define a single div for the "host container" for the page rendering. This is an instance of the PageControlNavigator class that's defined in navigator.js. In its data-win-options you specify "{home: }" for the initial page that's loaded.
Whenever you want to switch to another page, call WinJS.Navigation.navigate with the identifier for the target page (namely the path to its .html file). In response, it will fire some navigating events.
In response, the PageControlNavigator's handlers for those events will load the target page's HTML into the DOM, within its div in default.html. It will then unload the previous page's DOM. When all of this gets rendered, you see a page transition--and a smooth one because we can animate the content in and out rather than go through a black screen.
In this process, the previous page control's unload method is called, and the init/load/processed/ready methods of the new page control are called.
It's not too hard to convert a blank app template into a nav template project--move your default.html/.css/.js content into a page control structure, add navigator.js to default.html (and your project), and put a PageControlNavigator into default.html. I suggest that you create a project from the nav app template for reference. Given the explanation above, you should be able to understand the structure.
For more details, refer to Chapter 3 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition, where I talk about app anatomy and page navigation with plenty of code examples.
I have an asp.net-mvc website where there is a top section with a bunch of filter information and the middle section is a reports. I now have a few different report formats and I want to toggle between a few reports. I have it working by making them all partial views and loading them via ajax (to avoid loading the common info over and over again) but one issue i realized is that some of the different reports have different javascript that goes along with them. For now, I am loading up all of the javascript files in the main parent page but I realized that I am wasting a lot of resources by download and wiring up all of the jquery events even if i never actually view a report
Is there anyway I can pass some javascript along with downloading a partial view in asp.net-mvc so I only load this and wire up the events "on demand" as required (instead of always)
Of course you can. Just be aware that the effects of the code will stick around even if you later remove the code itself: any functions you defined will remain defined, any listeners you attached will remain attached (as long as their target elements persist)... so it would be a good idea to make a setup() and teardown() methods for the loading code, that you'd invoke from your controlling code, rather than just drop a bunch of code to execute as it loads.
However, I would say it would need to be a rather unique set of circumstances for me to employ this method; for most part, it would be much easier and efficient to just load all the code you need at once, to benefit from client caching if nothing else. Toggle the behaviour of your code, don't toggle the code.
Almost all web pages that I see designed to set the focus to an input box add the code into a body onload event. This causes the code to execute once the entire html document has loaded. In theory, this seems like good practice.
However, in my experience, what this usually causes is double work on the user, as they have already entered data into two or three fields and are typing into another when their cursor is jumped back without their knowledge. I've seen a staggering number of users type the last 2/3 of their password into the beginning of a username field. As such, I've always placed the JS focus code immediately after the input to insure there is no delay.
My question is: Is there any technical reason not to place this focus code inline? Is there an advantage to calling it at the end of the page, or within an onload event? I'm curious why it has become common practice considering the obvious practical drawbacks.
A couple thoughts:
I would use a framework like jQuery and have this type of code run on $(document).ready(.... window.onload doesn't run until everything on the page is fully loaded, which explains the delay you have experienced. $(document).ready(... runs when jQuery determines the DOM has been loaded. You could probably write the same sort of logic without jQuery, but it varies by browser.
I prefer to keep my Javascript separate from my HTML because it allows for a cleaner separation of concerns. Then your behavior is then kept separate from your document structure which is separate from your presentation in your CSS. This also allows you to more easily re-use logic and maintain that code — possibly across projects.
Google and Yahoo both suggest placing scripts at the bottom of the html page for performance reasons.
The Yahoo article: http://developer.yahoo.com/performance/rules.html#js_bottom
You should definitely place the script in the appropriate place if it means the correct user experience -- in fact I would load that part of the script (Used for tabbing inputs) before the inputs to ensure it always works no matter how slow the connection.
The "document.ready" function allows you to ensure the elements you want to reference are in the dom and fires right when your whole document dom is loaded (This does not mean images are fully loaded).
If you want you could have the inputs start out as disabled and then reenable them on document ready. This would handle the rare case the script is not ready yet when the inputs are displayed.
Well if you call it before whole page has loaded you really don't know if the element already has been loaded when you make your call. And if you make your call in pre-hand you should check if the element really exists even if you know it always should.
Then to make the call inline, which might seem ideal. But on the other hand it's really bad if a page takes that long to load that you can make several inputs during the loading phase.
Also you could check if input has been made etc.
Also it is possible to check if any input on page contains focus if($("input::focus, textarea::focus").length)... and otherwise set focus on desired input.
Use the autofocus HTML attribute to specify which element should initially receive focus. This decouples JavaScript and gracefully degrades in older browsers.