Home
Load HTML, JavaScript and CSS dynamically
Load CSS dynamically
CSS is loaded by creating a
style
element and attaching it to the
head
. They way that
style
elements are attached to the
head differs between browser but the code is fairly straight-forward.
Here is an example (make sure
to show the developer console).
Load HTML & JavaScript dynamically
Loading HTML is actually trivilial. All you need to to is fetch the HTML with
XMLHttpRequest
and replace the
innerHTML
attribute of
an element in the DOM.
Loading JS is also fairly easy. Here is an example:
source.
Make sure to open the developer console.
Compability
These examples should work in all browsers. It took my quite a bit of testing
to make the JavaScript loading work in both the Gecko (Firefox) and Blink/WebKit
(Safari and Chrome).
Alternative solutions
- Browserify - I use browserify for
developing complex apps. It brings the NodeJS style of modules to browsers and
there is also a port of many of the NodeJS API.
- Traceur - ES6
modules today
- webpack
- AMD - Has been around for a long time
and works well but there are better alternatives today.