0

I have a website whose navigation is all done via ajax (with jquery); each page is dynamically loaded into an element on the page. While I have a universal stylesheet and JS scripts, each page also has a page-specfic stylesheet and JS script. What is the most effect/efficient way to load these page-specfic scripts and stylesheets? On page load, most of the page-specfic scripts/stylesheets will not be needed. A page's scripts/stylesheet will only be needed when a user loads in (via ajax) a particular page. Should I load every single script and stylesheet at page load?

Another option would be to simply append appropriate <link> and <script> elements to the head when a page is dynamically loaded; however, would they be called? Also, would I need to remove the <link> and <script> elements when a different page is called (via ajax)? For the scripts, I could use jQuery's .getScript() function. What is the best approach to this in terms of efficiency and cross-browser support?

Thank you!

Leopold Joy
  • 4,524
  • 4
  • 28
  • 37

3 Answers3

1

Js and CSS are one time load and are browser cached (depends on your server conf as well)

So if you have an ajax, with just 1 JS inclusion. You could

  1. Insert this JS at the footer of your home page (lazy loading; pre-emptive thinking .. faster 2nd pages)

  2. Bring the include JS tag along with ajax response. (nothing complex here. browser makes fresh JS call)

  3. Combine all your JS/CSS into one combined JS, push it to home page head tag (eyeing performance and caching)

  4. once document ready, do similar to #1 using getScript() as you suggested

Faiz Mohamed Haneef
  • 3,418
  • 4
  • 31
  • 41
0

Well one way I know of that this can be done is with RequireJS, but the downside is that all the JS you have need to be defined as AMDs.

Don't know if you know anything about RequireJS, but its quite a neat library, you can imagine it as a dependency injector and loads files in async way. If you are interested you can check their docs:

TheCodeDestroyer
  • 763
  • 9
  • 29
0

Before I have commented what you could do with the CSS.

This is how you can work with js:

var script = document.createElement('script');
script.src = "path to your src";
// load event
script.onload = function () {
    //some staff
};
document.head.appendChild(script);

Also, for you, I'll recommend reading this gist.

Another good information.

Mr. Noddy
  • 1,530
  • 2
  • 16
  • 45
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37