Why to do this?

It may be a strange to hear when someone wanted to load a CSS file dynamically or even try to unload it.

Sure you can use jQuery to style the elements by adding inline styling, and removing the inline style using jQuery is not hard to do either.

As recently I have a project for VicTheme.com that requires a total CSS style change for ZetaOne Style Previewer. The changes must reflect the currently stored CSS file to reflect the current state of the configured style. In this case a simple inline style insert or removal will requires complex CSS parsing code in Javascript of PHP which will just slow the style change process and added bloat to the code.

So to solve this problem, why not just load the style dynamically and remove it when user change style? This will not requires any CSS parsing and can be done in just a few line of CSS.

Also as an added bonus, Initial page load time will be faster since the page will load CSS on demand only similar to image lazy load techniques.

How to do this?

First step is somehow pass the url for the CSS file to jQuery, in WordPress you can use function wp_localize_script() and in Drupal you can use drupal_add_js() function, for vanilla PHP just print the global js variable under <script /> tag will be suficient.

To simplify this tutorial, I will just use a statically dummy example url for the css script that needed to be loaded or removed.

(function($) {
  // Define the statistically coded URL
  var fileURL = "http://example.com/dummy.css";

  // Add the file directly to head
  // You can also use $.getScript() to do this via ajax
  var file = '<script id="dummy-file" type="text/css">' + fileURL + '</script>';
  $('head').append(file);

  // Removing file is also easy
  $('#dummy-file').remove();

})(jQuery);

This is the very basic code of how to load or remove CSS file, I'm sure more advanced JavaScript master will have more elegant and complex way to do this properly.