determine which js files to load in html on the fly - javascript

I am trying to set up a project which consist of htmls and javascript/ajax - jquery with many jquery plugins.
For each of many html pages, I have to use RequireJS and here is what i want..
I want to determine based on the property(return value from an ajax call) that I should load the minified files or non minified files
So I kind of need a mechanism to determine and decide (before the page load or as soon as the page starts loading) which js files I would want to load... and then go ahead with the load.
Is there a nice way to do this?

well,
take a look at this example:
the html
<!DOCTYPE html>
<html>
<head>
<title>My Sample Project</title>
<!-- data-main attribute tells require.js to load
scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>My Sample Project</h1>
</body>
</html>
scripts/main.js
$.ajax({
url: "http://server.com/fetchMeSomeData"
context: document.body,
success: function(data){
//this would be your sample callback
// you could be fetching the parameter to ask if it is debug state or not.
var isDebugSuffix = (data.isDebug)? "" : ".min";
require(["helper/util" + isDebugSuffix], function() {
//This function is called when scripts/helper/util.min.js is loaded but when the
//isDebug would be True, it would load scripts/helper/utils.js
//your other code can go here ...
});
}
});
hope this set you on your way...

Related

How do I include jQuery code in my node.js web app?

so I've been working on a (fairly simple) RESTful app using node.js, and I've made it towards the very last bit, now the only bit missing is using jQuery to manipulate the html page so I can edit the content of the html - and it's driving me absolutely mad.
I took the try.jquery.com tutorial, and it was pretty smooth; I'd by no means call myself a master of jquery, but I have very little trouble writing the code for basic html manipulation, except I never really considered where the jquery code would go. I've tried a bunch of different stuff and only one (really inconvenient) way has worked, so I was wondering if I could get some clarification.
(Note: all the js files are in the root folder, and index.html is in root/public; and I'm basically just running app.js through npm/package.json)
I've tried including the jQuery code in the main app.js file:
app.js
//some imports/requires here
var $ = require('jquery');
//more imports/requires here
//error; document is undefined
$(document).ready($('h1').text('Im Here');
app.get('/', function (req, res) {
res.sendFile(__dirname+'/public/index.html');
});
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<title>Inspiratorator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script="../app.js"></script>
I've tried including the jQuery code in its own file (tried just letting the code sit in the js file, and tried exporting the code as a function and calling it from app.js - both did nothing):
jusQueryin.js
var $ = require('jQuery'); //tried with and without this
$(document).ready(function () {
$(' button ').on( 'click', $('h1').text("I'm here") );
console.log('kpa');
});
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<title>Inspiratorator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script="../jusQueryin.js"></script>
I've also tried (this worked, but I don't know how I would deal with the code in here from other .js file, if it is possible):
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<title>Inspiratorator</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
$(document).ready(function () {
$(' button ').on( 'click', $('h1').text("I'm here") );
console.log('kpa');
});
</script>
I've also tried different variations(i.e. including the 2nd part of the ready function in a function (or not), using an onClick event inside the dom.ready function, etc..), but the only one that worked was the last approach
Ideally, I'd like to be able to use the jQuery code inside app.js, less ideally would be in its own file; or if I have to include it inside the html file for some reason, I would at least need to be able to communicate with the code in the script block so that I can give it info from the database and so on.
Remeber one thing jQuery needs a window object to work. The first functionality of jquery is as dom query, dom is within a window object. As a result you must load the jquery and attach it to a window object.
As a node app you will have a browser window as a view to your app. Try adding jquery to that window from a CDN, add your requires there, voila the containing scope(window) which contains jquery now as global passes it also to the newly required file.
Error: jQuery requires a window with a document
index.html
<script>
window.$ = window.jQuery = require('./node_modules/jquery');
</script>
<script>
var UI = require('./controllers/UI');
UI.init(window);
</script>
Now var UI, which is a module in my case, contains

Avoid Render Blocking by plugins which have both css and js dependencies

I am using a jQuery plugin it has plugin.css and plugin.js as dependencies and code is in script.js. I cant have plugin.js and script.js merged because i am using plugin only on one webpage of my website.
In order to make sure plugin.css is loaded before execution of plugin.js and script.js, normally I have no option but to have plugin.css in <head> which causes render blocking(until all resources in head are loaded,
browser doesnt render html).
Normal Way: Having CSS in <head> and JS before </body>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/plugin.css">
</head>
<body>
// content goes here
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="/js/plugin.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
Proposed Way: Load CSS and JS via ajax calls and inject them when all of them are loaded, using jQuery $.when promise
<!DOCTYPE html>
<html>
<head>
</head>
<body>
// content goes here
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script class="load-plugin">
$(document).ready(function(){
var loadPlugin = {
css : $.ajax({ url: $(".jquery-plugin-css").data("src") }),
js : $.ajax({ url: $(".jquery-plugin-js").data("src")}),
};
var scriptJs = $.ajax({ url: $(".script-js").data("src") });
$.when(loadPlugin.css, loadPlugin.js, scriptJs).then(function(){
loadPlugin.css.done(function(data){
$(".jquery-plugin-css").html(data);
});
loadPlugin.js.done(function(data){
$(".jquery-plugin-js").html(data);
});
scriptJs.done(function(data){
$(".script-js").html(data);
});
});
});
</script>
<style class="jquery-plugin-css" data-src="/css/plugin.css"></style>
<script class="jquery-plugin-js" data-src="/js/plugin.js"></script>
<script class="script-js" data-src="/js/script.js"></script>
</body>
</html>
This improved my first render time from 3.4 secs to 2.4 secs and total page load time from 8.5secs to 8secs.
But this has some limitations:
Publicly hosted urls cant be used because the urls inside the plugin files like background-images inside css files if mentioned relative to their directory then the path changes after code is pasted into html.
As the injected code is not part of the source files or external scripts they cant be debugged in developer tools.
This way of lazyloading plugins has pros and equal amount of cons. Can anyone suggest is it worth it to do it this way or any better way to do things.
What I would try is:
Combine the JS files so that the dependent code is after plugin.js
Insert a script at the bottom of the page to dynamically load the CSS first and the combined JS second. If you need example code, you might look at https://github.com/filamentgroup/loadJS/ and https://github.com/filamentgroup/loadCSS/.
Using this approach, neither the CSS nor the JS blocks rendering. The CSS is appended to the DOM, so there should be no problems with relative URLs.

Prepare jquery before jquery and page load

I have recently discovered the new trend of including all .js script at the end of the page.
From what i have read so far seems pretty ok and doable with an exception.
The way I am working is using a template like:
<html>
<head>
<!-- tags, css's -->
</head>
<body>
<!-- header -->
<div id="wrapper">
<?php
include('pages/'.$page.'.php');
?>
</div>
<!-- footer -->
<!-- include all .js -->
</body>
</html>
Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.
I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.
Thanks!
Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.
Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:
$(document).ready(function(){
if($('.thumbnail').length) {
// your thumbnail code
}
});
A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:
if($('.thumbnail').length) {
require(['ThumbnailScript'], function(ThumbnailScript){
ThumbnailScript.init();
});
}
The best way you can go is create a separate file for this code.
Let's name it app.js. Now you can include it under the jQuery inclusion.
<script type="text/javascript" src="app.js"></script>
This will prevent code repeat.
One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:
$(document).ready(function(){
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
})

Reuse elements of HTML

I'm writing a static web site that uses JQuery to make some AJAX calls to a RESTful API and populate the page with data.
The site functions correctly (and quickly), everything is good.
As I extend the site and add additional pages, I'm noticing that I'm duplicating certain regions on every page.
For instance, each page shares a common header element.
<header>...Some non-trivial content...</header>
Rather than repeat this definition on each page is there some mechanism, by which, I can define this section once and include it in each document.
Remember that the pages must be served statically but any standard complaint browser functionality can be utilised.
Is there a good way to do this, and what is it or, will I have to abandon DRY principles for this aspect of my client side code?
There's definitely some ways to achieve this. You could either do it using some features of your server-side language that allows to include the content of a page in another page, or if you do not have any server-side technology, you could simply put that code in it's own html document and load it's content using AJAX.
In jQuery it could look like:
$('#header').load('header.html');
However, if the content isin't static for all pages, you could always define a JS module that would be responsible to render this header. You module could make use of a client-side templating engine, like Mustache, Handlebars, etc. However you do not have to use any of these.
Here's a simple example:
DEMO
//in somefile.js, please note that you should namespace your modules
var Header = {
//default config
config: {
el: '#header',
title: 'Some title'
},
init: function (config) {
var cfg = this.config = $.extend({}, this.config, config);
$(cfg.el).html('<h1>' + cfg.title + '</h1>');
}
};
$(function () {
Object.create(Header).init({
title: 'Some other title'
});
Object.create(Header).init({
el: '#header1',
title: 'Yeah'
});
});
As I mentioned in the comment, this is how I do it:
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
You could use jQuery's ajax as to load the header file. In each file you could load the html like so:
$('#header').load('header.html');
Since you're already using AJAX calls to populate your site with data, you could do the same for the common regions.
Just store the HTML for those regions in a separate file and load it in the page with AJAX. Also, you can work with caching using the Cache-Control headers on that file so you don't reload the entire content from the server with each page load.
If you're using straight HTML, you could do it with a SSI include command or by creating a template page and including it in jQuery. Both of these links might help you
Include another HTML file in a HTML file
and
http://www.htmlgoodies.com/beyond/webmaster/article.php/3473341/SSI-The-Include-Command.htm
It looks like this in modest:
main.xhtml
<?xml version='1.0' encoding='UTF-8'?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<include>reusablePiece</include>
</head>
<body>
<reusablePiece/>
</body>
</html>
reusablePiece.xml
<header>...Some non-trivial content...</header>
Very simple would be the jQuery .clone() function.
If you have more complex content I recommend looking at Handlebars.js which is a full fledged JS templating engine.

Javascript - Dynamically load a fragment of HTML and run script

I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html) can dynamically get and insert the HTML I want (existing.html) using XMLHttpRequest. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html and run the script which populates it?
Once the page has loaded, add in existing.html via innerHTML. Rather than calling its functions, just let existing.html's code execute, which will do the same as if it were in the onload section.
EDIT: Or, you could just correct that typo you have. initExistingHTML != initExistingHtml.
lol

Categories

Resources