Importing Elements and Layouts with HTML and JS

Exploring the possibilities of modern web development


I've been exploring just how much I can separate the back end logic from the front end, and with my expedition I learned that there is one challenging area to face: How do I replicate layouts? Sure, there’s quite a few frameworks that talk about importing elements and replacing content on your pages using a JSON response; however, there hasn’t been much talk on solving the layout issue.

What inspired me to look into this was basically trying to solve a feature in which a layout would change depending on the type of user. Sure you could easily retrieve the user information from the session and then switch the layout based on their credentials, but what if you wanted to handle all that logic on the front end?

So if you are from the future, I’m sure you have heard about the shadow dom. For those that haven’t, basically you can create elements that have a custom defined stylesheet, markup, and a whole lot more in which is possible to build templates from (see: http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/). But what about now? I’m not trying to solve the issue of using Shadow Dom now, but I am able to come pretty close or at least I’ve written something that’s a fun science experiment.

The concept is simple: You define an element that points to the source of an HTML file which includes the scripts, CSS, and markup needed. When opening any page, the script will execute a loop where it searches the contents of the page to find any include attributes, load their corresponding files, replace the include element with the new source, and then continue into there is no more include attributes found on the page. From there, once we have loaded all the CSS files, we will show the page and then start loading all the JS files.

The markup would look like this:

<div include=”layouts/login.html”>Hello World</div>

Which then would point to an HTML file which might have:

<head>
… css & js scripts…
</head>
<body> <div class=”myLayout”> {{content}} </div>
</body>

Which finally after the page is ready to go shows this:

<head>
… css & js scripts…
</head>
<body> <div class=”myLayout”> Hello World </div>
</body>

For any element/layout/include I have two parts: The head and the body. The head is where all the scripts and CSS includes, and the body is where the content of the include will reside. That’s the basic idea. I tried to keep it relatively simple for people to understand so you don’t have to learn any new concepts, just simple a continuation of what you already know.

Another cool concept I came up was include-checks which allows you to run a routine before loading an include. This way you can have things like “Check to see if I am authenticated” and load a certain layout. It’s all pretty flexible.

Tis my first post. I couldn't help but try out the cleanliness of Medium ☺