Keep, but deactivate stylesheets & scripts - javascript

I have 4 pages, I use ajax and historyPopState to change betweens them. But there is a problem since the pages are very different they use different stylesheets and scripts. I could just download them over and over again, but I wanted to ask if there is a way how to keep it onpage, but only disabling it for a moment and reenable them when needed.
PS.:Those 4 pages have one stylesheet & one script in common.
PPS.: And I can't set headers (not access to all things in server)

In javascript you can disable stylesheets by accessing the styleSheets object on the document and setting disabled to true:
(tested in Chrome and IE9. I couldn't find any useful statistics on compatibility for this)
document.styleSheets[0].disabled = true

Related

Page Specific JavaScript using Content Security Policy (CSP) [duplicate]

This question already has answers here:
Best way to execute js only on specific page
(5 answers)
Closed 5 years ago.
I want to use Content Security Policy (CSP) across my entire site. This requires all JavaScript to be in separate files. I have shared JavaScript used by all pages but there is also page specific JavaScript that I only want to run for a specific page. What is the best way to handle page specific JavaScript for best performance?
Two ways I can think of to workaround this problem is to use page specific JavaScript bundles or a single JavaScript bundle with switch statement to execute page specific content.
there is lots of ways to execute page specific javascript
Option 1 (check via class)
Set a class to body tag
<body class="PageClass">
and then check via jQuery
$(function(){
if($('body').hasClass('PageClass')){
//your code
}
});
Option 2 (check via switch case)
var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname
switch (windowLoc) {
case "/info.php":
//code here
break;
case "/alert.php":
//code here
break;
}
Option 3 Checking via function
make all the page specific script in the function
function homepage() {
alert('homepage code executed');
}
and then run function on specific page
homepage();
Sorry, I know this ended up being a long read, but it'll be worth it to do it as you'll be able to make the choice that's right for your site. For a tl;dr, read the first sentence of each paragraph.
First of all, no matter which route you choose you should put all of the JS common to each page in the same file to take maximum advantage of caching. That's just common sense. Also, in all cases, I assume you're using a competent minifier since that will make a bigger difference than anything else. Packagers also exist if you need one of those -- Google is your friend if you need either of these.
For the page specific JS, you should decide whether it's most important to have your first page load (the user's first contact with your site) be 'fast', or if it's most important to have the following page loads (the user's first contact with any given page) be 'fast'. Modern browser caching is quite good now, so you can rely on the browser loading from cache whenever it can. In general, if it's most important for the first page load to be fast, then create separate JS files (this way, the user isn't stuck downloading 10 MB of data before they even get to your site). If not, then put all the JS in the same file, keeping in mind that if one page has significantly more JS than others, it will adversely affect the load time of every page on your site. Note that this extra load time can be mitigated with the use of async or defer tags, more on that later.
Consider the case where page A has 5 KB of JS and page B has 5 MB of JS. If you put both scripts in the same file, page A will load more slowly (since it needs to load ~5 MB of JS) but page B will load much faster due to the JS file being cached already. If you keep them separate, page A will load much faster than page B, but there will be an average speed decrease compared to the first case. If one page doesn't have significantly more JS than another, use separate files. You'll encounter much better average load time since the "savings" of loading the big file ahead of time will be greatly diminished (you'll also avoid the issue mentioned below).
Another consideration is whether one of the JS files will change often, as this will invalidate the cached version and require the browser to redownload it. If you put all your JS together and only one of the files is volatile (especially if it's a page not often visited, such as a registration page), the end user will face a higher average load time than if you keep them separate. Stack Overflow themselves took an interesting approach to this. It appears they have a function to invalidate the cache of JS unrelated to the page and load it (if necessary) when the JS on the page loads from the cache to save loading time later.
One more thing! Beyond all this, you should also decide whether or not you should use async or defer in your script tags since you're migrating to fully "external" JS.
async allows the page to load and display to the user before the JS is finished downloading. This is a great way to hide the download of a big JS file if you decide to go the "one file to rule them all" route. However, you might also find the JS needs to be downloaded and execute in order for the page to display properly (as is the case when not using async or defer).
As a result, it might be a good idea to use a hybrid of the two suggestions and split your js into individual files that need to be loaded per page for the page to display correctly (one per page), and put all the js that doesn't into a script that loads through an async or defer tag (this being the "one big file"). defer lets the browser load it in the background after the page is displayed to the user.
Ultimately, only you can make the decisions that are right for your app. There's no one magic option that will work in all cases, but that's the reality of software design/engineering. I hope I've made the process clearer for you so you can arrive at the right choice more easily, though.

Dynamically modify content_scripts.matches in FireFox extension

So I'm trying to follow the instructions for a firefox extension using WebExtensions and I want to attach a content script to certain pages (as discussed here: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Modify_a_web_page ).
Problem is I don't want to specify the set of pages I want the content_script to run on in manifest.json when I write the extension but load it from local storage, i.e., I have an options page set up where the user can specify the pages the content script should be run on. Is it possible to dynamically change the list of pages to be modified that is normally set using the content_script directive in manifest.json?
Thanks
No, there is no way to modify the URLs into which injection will occur for a manifest.json content_script (either CSS or JavaScript). The specified code will be injected in all matching URLs. This is for multiple reasons.
One of the reasons this is not possible is security/transparency to the user. The manifest.json explicitly declares which URLs your content script will be modifying, states that it will be modifying the active tab, or that it will have access all URLs/tabs. If you were permitted to change the URLs, then you would effectively be given the ability to access all URLs without explicitly declaring that you are doing so.
Yes, it would be possible to have a way to declare that you are going to do so. Chrome has an experimental way to do so with chrome.declarativeContent. In Chrome this is considered experimental, even after being available for a couple/few years. It is not available in Firefox. When it will be available, or even if it will be available in Firefox is unclear. In addition, even in Chrome, it lacks some features available to other methods of injecting scripts (e.g. run_at/runAt).
In order to have complete control over injecting, or not injecting, you will need to perform the injection via tabs.insertCSS() and/or tabs.executeScript(). Injecting, or not injecting, scripts and CSS with these methods is fully under the control of the JavaScript in your extension. It is possible to get similar functionality using these methods to what you obtain with manifest.json content_script entries, but with more control. This greater control comes at the expense of greater complexity.
How about that? There is a bunch of events to listen, you can pick any one which would satisfy uour requirements:
onBeforeNavigate
onCommitted
onDOMContentLoaded
onCompleted.
The documentation is here. And this is an example of how to make red background on subdomains of example.com. Of course, you can build the list of URL filters dynamically, this is just a PoC:
browser.webNavigation.onCommitted.addListener(
function(details) {
browser.tabs.insertCSS(details.tabId, {code: 'body {background:red}'})
},
{url: [{hostSuffix: '.example.com'}]}
);

jquery initiates automatic call for other js files

I see some strange behavior when I check network tab on chrome tools. jQuery is initiating call to other js files of page. These other files are already loaded but jQuery is adding ?_=some_random_number at the end and calling those files again.
jQuery does not load other javascript-files by default. You must have another library that loads these resources. And by the way, the ?_={timestamp} is used to invalidate browser-caching (the url changes every second, so every second a real request is made, not just a browser-cache lookup).
You can try to enforce the ajax-caching mechanism with:
$.cache = true;
while initializing your code. Thus, the requests will be cached by your browser. But, be aware, that this might tamper with other parts of your code. A better way would be to identify the reason why these extra resources are loaded, and avoid loading.

How to make page loading feel faster?

I want to decrease the time taken by my pages to load and be displayed, assuming I start with an empty browser cache, and the pages may or may not have inline css and javascript in the html file. does changing the order in which files are sent to the browser decrease the display time, and thus make pages seem to be loading faster?
For example if a page has some .css, .js, .png files and so on, would loading the css first, display things faster?
And is there a standard/specific order to load file types?
Here are few steps that could optimize the performance of your web pages.
put css at top.
put javascript at bottom.
cache everything.
set far future expire header.
return 304 when appropriate.
use unique url for css and js for propagating the change.
apart from that use ajax wherever required.
Beware of too many HTTP connections. It takes time to establish an HTTP connection and it can easily eat up loading time if you have many elements linked in your HTML file.
If you have many small icons, glyphs, etc. combine them into a sprite so only one image is loaded. Facebook for instance makes use of the sprite technique - you can see that if you inspect the images it loads.
You can also consolidate your CSS files into one file - same with Javascript files.
Also, if you have JavaScript that affects the content of your page when it loads then make sure to use the event that notifies you when the DOM is ready, instead of waiting for the body loadevent which doesn't trigger until all resources, such as images, CSS files, JavaScript etc is loaded.
js files block page loading until they're executed. When possible, include those before closing body
At first make sure that your webhoster has no slow servers. This can happen on very cheap shared site webhosters. Than you should check that you remove all unnessesary stuff from your html output. Than you could check if your content is dynamic or static. If it is dynamic try to convert it to static content.
In some conditions you can simply activate the caching functions of a CMS that should also help to send the website content faster. Just on slow connections it could be better to use gzip to compress the output stream. But this costs time. The server and also the client have to compress/decompress. You have to check that too.
If you use javascript and the execution is delayed you could also use the ready event to execute your javascript after the html document is loaded (and not all images and so on) like using the document.onload event.
You can save your page load time to use few trick like :- CSS image sprites rather than call every single image for every single purpose this will Minimize your website's HTTP Requests, remove unnecessary div tags or unnecessary code from your HTML-Markup & CSS
Where we can get good results through CSS and so we should not use Jscripts there.
Should make always clean HTML-Markup without any irreverent code.
Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.
The solutions turned out the simple, combine all the different files into a single large file and compress that file using zip. Unfortunately, if you do this manually you are going to run into maintenance problems. That single compressed file is no longer editable. So after editing one of the original source files you will have to re-combine it with the other files and re-compress it.

LESS (dynamic style sheet language) and Resource Loaders

I am currently looking at changing from using css to LESS in my current project. A few things to mention before I get to the question are:
1) The project is purely clientside (Html/Js/Css) so there is no server side component for the website (although there is a web service it calls via CORS)
2) I load almost everything via resource loading frameworks, currently I am using yepnope
So given the above I need to be able to get the LESS styles to be processed clientside, but as I am using a resource loader and more css/less could be loaded after the initial page load has happened I was wondering if:
1) Does Less work with content loaders when using client side processing? As it says:
Client-side usage
Link your .less stylesheets with the rel set to “stylesheet/less”:
<link rel="stylesheet/less" type="text/css" href="styles.less">
Then download less.js from the top of the page, and include it in the <head> element of your page, like so:
<script src="less.js" type="text/javascript"></script>
Make sure you include your stylesheets before the script.
I think I may be able to tell yepnope how to handle less files and give them the required element attributes. If I can providing the less resources are brought in before the less javascript will it be ok?
2) Is there any manual way to tell it what to process in javascript?
This would cover the case where everything has been loaded for the current page, the user clicks a button which dynamically loads a new template which is displayed in the current page, this may require new less resources to be loaded, but the less.js file has already been included.
Hopefully the above gives you some context as to what I am trying to do and what the 2 questions are.
Yes you can.
Reading this post Load less.js rules dynamically and adjusting it a bit:
less.sheets.push(document.getElementById('new-style-1'));
// Add the new less file to the head of your document
var newLessStylesheet = $("<link />").attr("id", "new-style-1").attr("href", "/stylesheets/style.less").attr("type", 'text/less');
$("head").append(newLessStylesheet);
// Have less refresh the stylesheets
less.refresh(true);
You could also generate all the CSS in your development environment and put it in one file.
There are lots of options. The easiests way would be to use an application. You could use apps like http://incident57.com/less/ for Mac. You can even compile online: Search for something as "lessphp".

Categories