how to inject javascript at header and body using gulp - gulp

I want to inject javascript library inside head tag and my customized and my own code at body using GULP.
For Example:
<html>
<head>
<!-- injectJS -->
<script src="jquery.js">
<script src="d3.js">
<!-- injected -->
</head>
<body>
<!-- injectJS -->
<script src="index.js">
<!-- injected -->
</body>
</html>

I've been using gulp-template to do exactly this. Your index.html would then have to be adjusted. e.g.:
<% scripts.forEach( function ( file ) { %>
<script type="text/javascript" src="<%= file %>" inline></script>
<% }); %>
In this example your gulpfile task would look something like:
gulp.task('index', () =>
gulp.src('src/index.html')
.pipe(template({scripts: ['script.js', 'another-one.js']}))
.pipe(gulp.dest('dist'))
);
Another way to achieve this would be using gulp-inject. I prefer gulp-template though.

Related

Is it possible to ignore some lines in html on building html with Gulp?

I have a html setup in my app folder and this is copied in the dist folder by gulp.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../dist/css/style.css">
</head>
<body ng-app="myApp">
<div ui-view></div>
<!-- build:jsLib js/libs.js -->
<script src="../libs/angular-ui-router/release/angular-ui-router.js"></script>
<!-- endbuild -->
<!-- build:jsApp js/app.js -->
<script src="app.js"></script>
<!-- endbuild -->
<script src="../libs/angular-mocks/angular-mocks.js"></script>
<script type="text/javascript">
angular.module('testApp', ['mockService', 'productServicesApp', 'ngMockE2E']);
</script>
</body>
</html>
That part is used to make fake service calls and I don't want it in deployment files:
//something like *ignore this*
<script type="text/javascript">
angular.module('testApp', ['mockService', 'productServicesApp', 'ngMockE2E']);
</script>
Is is possible to ignore this line with gulp?
Yes this is possible. A nice plugin to do this would be the gulp-remove-code plugin.
Below is an example of how you would use it
HTML:
<div>
<!--removeIf(production)-->
<div class="sandbox-banner">Running in sandbox environment</div>
<!--endRemoveIf(production)-->
<span>Removing code is ready.</span>
</div>
GULP:
var gulp = require('gulp');
var removeCode = require('gulp-remove-code');
HTML_FILES = '/path/to/html/**/*.html';
gulp.task('clean-html', function() {
return gulp.src(HTML_FILES)
.pipe(removeCode({ production: true }))
.pipe(gulp.dest('dist/'));
});
And then you just call it by saying
gulp clean-html
Anything inside of those comment tags will be removed. Also, the object passed to removeCode is not namespace specific. So you can change the naming to whatever.

Ajax .load() function not working

.load() only works on files coming from a server, so it will work later as I'm going to put this on a server
Edit: This code works on firefox but not on chrome
I've been trying to use ajax to load a webpage after selecting an option but the script doesn't even seem to load
here's the script + html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="DaVinciRace.css" />
<title> Da Vinci Race 2014-2015 </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
</head>
<body style="background:#f2f2f2;">
<div id="logo">
<img src="Resources\DVRLogo.png"/>
<!-- <p class="text">Da Vinci Race</p> -->
</div>
<div id="options" style="background:#0c0c0c; float:right;">
<div class="menu">
<div class="chronometre" ></div>
</div>
</div>
<div id="DVRChrono">
</div>
<script>
$(document).ready(function(){
$("#options").on("click", ".chronometre", function() {
$( "#DVRChrono" ).load( "Chronometre.html" );
})
});
</script>
</body>
</html>
the document "Chronometre.html" is in the same folder as this html page
I feel like I'm missing something obvious but can't for the life of me figure out what it is
Try this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" ></script>
<script>
(function($){
$("#options").on("click", ".chronometre", function() {
$( "#DVRChrono" ).load( "Chronometre.html" );
})
})(jQuery)
</script>
This isn't adding a click handler:
$("#options").on("click", ".chronometre", function() {
// code
});
Because it executes before the #options element exists on the page. The code is executing without error, the jQuery selector simply isn't finding anything. So there are no elements to which a handler can be attached.
You can fix this either by moving the code to the end of the page or by wrapping it in the document.ready handler:
$(function() {
$("#options").on("click", ".chronometre", function() {
$( "#DVRChrono" ).load( "Chronometre.html" );
});
});
Additionally, your script tags are broken. Each tag should have either a src or content, but not both. Separate them:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
// your code
</script>

How to copy and inject the main-bower-files in one step using gulp?

When deploying my app I want to copy the bower dependency to the deploy directory and inject the links to these files into the index.html that is also in the deploy directory.
Each step alone works perfectly by I'm not able to combine them.
Copy the files:
return gulp.src(mainBowerFiles(), { read: false })
.pipe(gulp.dest('./deploy/lib/'));
Injecting the files:
return gulp.src('./deploy/index.html')
.pipe(plugins.inject(
gulp.src(mainBowerFiles(), { read: false }), { relative: true }))
.pipe(gulp.dest('./deploy/'));
I think that I should do this in one step to keep the correct order of the dependent files.
I tried this combination but it did not work out.
return gulp.src('./deploy/index.html')
.pipe(plugins.inject(
gulp.src(mainBowerFiles(), { read: false })
.pipe(gulp.dest('./deploy/lib/'), { relative: true })))
.pipe(gulp.dest('./deploy/'));
I recommend wiredep:
You add a block to your html:
<html>
<head>
</head>
<body>
<!-- bower:js -->
<!-- endbower -->
</body>
</html>
and your wiredep task looks like:
// inject bower components
gulp.task('wiredep', function () {
var wiredep = require('wiredep').stream;
gulp.src('app/*.html')
.pipe(wiredep())
.pipe(gulp.dest('app'));
});
Which will add the deps to your html as such:
<html>
<head>
</head>
<body>
<!-- bower:js -->
<script src="bower_components/foo/bar.js"></script>
<!-- endbower -->
</body>
</html>
You can then combine this with useref to order all your project's javascript dependencies
html block
<!-- build:js scripts/app.js -->
<!-- bower:js -->
<script src="bower_components/foo/bar.js"></script>
<!-- endbower -->
<script src="js/yourcustomscript.js"></script>
<!-- endbuild -->
gulp task
gulp.task('html', ['styles'], function () {
var assets = $.useref.assets({searchPath: '{.tmp,app}'});
return gulp.src('app/*.html')
.pipe(assets)
.pipe(assets.restore())
.pipe($.useref())
.pipe(gulp.dest('dist'));
});
Take a look at how generator-gulp-webapp does things: https://github.com/yeoman/generator-gulp-webapp
Note: the $.plugin syntax assumes var $ = require('gulp-load-plugins')();

What is the <%= %> tag in html?

I have the following code from a html page:
<div class="bd">
<h1><%= user.fullname %></h1>
</div>
What is the <%= %> tag? Is this standard html? I never encountered it before. (user.fullname is a javascript variable)
Here is the full code of the page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/layout.css">
<link rel="stylesheet" href="css/styles.css">
<script language="javascript">
// We use this code for handling unexpected errors.
// Using alert, we are sure that the user get notified in a Mobile device.
// We add this code at the begining of the index.html and we use only native javascript functions.
window.onerror = function(msg, url, lineNumber) {
if (typeof(msg) === "string") {
var error = msg + "\n\nFile: " + url + "\nLine: " + lineNumber;
// Ommit cordova and 3rd party libs errors.
if (url.indexOf("cordova.js") == -1 && url.indexOf("externallib") == -1) {
window.alert(error);
}
} else {
var error = msg;
}
// This may help debugging if we use logging apps in iOs or Android.
if(typeof(console) !== "undefined" && typeof(console.log) === "function") {
console.log(error);
}
// Let default error handler run.
return false;
};
</script>
<script src="cordova.js"></script>
<script src="childbrowser.js"></script>
<script src="webintent.js"></script>
<script src="PushNotification.js"></script>
<script src="externallib/jquery.min.js"></script>
<script src="externallib/jquery.touchSwipe.min.js"></script>
<script src="externallib/md5.js"></script>
<script src="externallib/matchMedia.js"></script>
<script src="externallib/matchMedia.addListener.js"></script>
<script src="externallib/underscore.js"></script>
<script src="externallib/backbone.js"></script>
<script src="externallib/backbone-localstorage.js"></script>
<script src="lib/mm.js"></script>
<script src="lib/mm.panels.js"></script>
<script src="lib/mm.util.js"></script>
<script src="lib/mm.lang.js"></script>
<script src="lib/mm.db.js"></script>
<script src="lib/mm.tpl.js"></script>
<script src="lib/mm.cache.js"></script>
<script src="lib/mm.settings.js"></script>
<script src="lib/mm.widgets.js"></script>
<script src="lib/mm.sync.js"></script>
<script src="lib/mm.emulator.js"></script>
<script src="lib/mm.rdebugger.js"></script>
<script src="lib/mm.fs.js"></script>
<script data-main="lib/app.js" src="externallib/require.js"></script>
<script language="javascript">
// We should wait to phonegap, if not, we get errors like:
// http://rickluna.com/wp/2012/04/solving-the-connection-to-the-server-was-unsuccessful-error-in-androidphonegap/
$(document).bind('deviceready', function() {
MM.log('Deviceready fired');
MM.deviceReady = true;
// Store the device locale for further uses.
navigator.globalization.getLocaleName(
function (locale) {
MM.lang.locale = locale.value;
MM.log("Device locale loaded: " + locale.value);
},
function () {}
);
// Disable the back button, exists the app.
document.addEventListener("backbutton", function() {
MM.panels.goBack();
}, false);
// Call deviceIsReady function in plugins.
// Plugins may not be able to listen for the deviceready event because it's possible that it was fire
// when plugins whasn't loaded, we use a timeout of 5 seconds.
setTimeout(function() {
for (var el in MM.plugins) {
var plugin = MM.plugins[el];
if (typeof(plugin.deviceIsReady) == 'function') {
plugin.deviceIsReady();
}
}
}, 5000);
MM.fs.init();
});
// This function is for handling when the app is opened using a custom URL SCHEME.
function handleOpenURL(url) {
MM._appLaunchedByURL(url);
}
</script>
<style id="mobilecssurl"></style>
</head>
<body>
<div id="add-site" style="display: none">
</div>
<div id="manage-accounts" style="display: none">
</div>
<div id="main-wrapper" style="display: none; background-color: white">
<div class="header-wrapper">
<header class="header-main">
<nav class="nav-main">
<ul class="nav">
<li class="nav-item home menu-home">
<a href="#" class="ir" id="mainmenu">
Home
</a>
</li>
</ul>
<span id="page-title"></span>
</nav>
</header>
</div>
<div id="panel-left" class="panel user-menu"></div>
<div id="panel-center" class="panel"></div>
<div id="panel-right" class="panel"></div>
</div>
<div id="app-dialog">
<div>
<div class="modalHeader">
</div>
<div class="modalContent">
</div>
<div class="modalFooter">
</div>
<div class="modalClear"></div>
</div>
</div>
<script type="text/template" id="menu_template">
<header>
<div class="media">
<div class="refresh app-ico">
<a href="#refresh">
<img width="16" height="16" src="img/reload.png" border="0">
</a>
</div>
<div class="img">
<img src="<%= MM.util.getMoodleFilePath(user.profileimageurl) %>" border="0">
</div>
<div class="bd">
<h1><%= user.fullname %></h1>
</div>
</div>
</header>
</body>
</html>
What is the <%= %> tag in html?
There is none. There are several templating engines that use <% and %> to delimit either templates or code blocks, though: Active Server Pages (ASP), JavaServer Pages (JSP), probably others. Those usually do server-side processing and replace the text in the <% ... %> with whatever should go there.
For instance, in your example
<h1><%= user.fullname %></h1>
if the user object's fullname property is "Joe Bloggs" when the resource is requested, the engine will swap that in for that token before sending the text, so what the browser actually sees is
<h1>Joe Bloggs</h1>
In your case, as you point out, the processing is happening client-side. Your <% ... %> tokens are within <script type="text/template">...</script> blocks, so the < isn't at all special. (Before DCoder pointed that out to me, I had a complex explanation here of why it worked...but then, er, DCoder pointed out that they were in script blocks, so...)
DCoder also identified that these are templates being handled by backbone.js, which reuses underscore.js's templates.
What is the <%= %> tag in html?
Like T.J. Crowder said, that is not an HTML tag, it comes from a client-side templating engine that happens to use these expressions to indicate the beginning/end of dynamically interpolated content.
How do I find out what templating engine is used? (it's not ASP or JSP)
Based on the fact that your page loads backbone.js, the template engine is most likely backbone's template engine, which is actually borrowed from underscore.js.
That's either ASP.NET or JavaScript markup that you're seeing.
That's usually a form of server side programming. It could be JSP (in Java), ASP or even PHP (with asp tags enabled). It will replace the contents (at server response time) of the <%= %> with the server side variable's value.
The statement '<%= user.fullname %>' evaluates the property 'user.fullname' and renders it as a string. The 'user' object could exist as a property on the page or could be a static class type.

Loading Underscore templates in HTML

I am trying to load templates from a file into an HTML file using a script tag. I want to use this as a template in UnderscoreJS - but I'm not able to load the file:
//main.js
this.template = _.template($("#add-question").html());
console.log("testing");
console.log(this.template({
question: "How are you doing?",
yesOrNo: true
}))
//console output:
testing Main.ts:37
Main.ts:38
//main html file:
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
<script type="text/template" id="add-question" src="client/add-new-question.html"></script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js" type="text/javascript"></script>
<script src="https://rawgithub.com/jashkenas/underscore/master/underscore-min.js"></script>
<script data-main="main.js" src="build/require.js"></script>
</body>
</html>
// client/add-new-question.html
<form id="testForm">
<span>"<% question %></span>
<input id="questionInput" type="text">
<span>"<% yesOrNo %></span>
<input id="typeInput" type="checkbox">
</form>
Update:
Here's the updated HTML in in which I've tried loading the html though a script tag in the body. Still doesn't work. This is how its expected to be done when rendering the template with UnderscoreJS. I want to be able to load the template with requireJS but render it using the underscoreJS template function.
<body>
<script type="text/template" id="add-question">
<form id="testForm">
<span>"<%= question %></span>
<input id="questionInput" type="text">
<span>"<%= yesOrNo %></span>
<input id="typeInput" type="checkbox">
</form>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="https://rawgithub.com/jashkenas/underscore/master/underscore-min.js"></script>
<script data-main="main.js" src="build/require.js"></script>
</body>
You have to use <%= to output variables instead of <%.
It looks like you are using requirejs.
So you could also use the tpl extension and store your underscore template in .tpl files:
https://github.com/ZeeAgency/requirejs-tpl
define(['tpl!client/add-new-question.html'], function(tpl) {
console.log(tpl({
question: "How are you doing?",
yesOrNo: true
}));
});
Links:
How to use underscore.js as a template engine?
and underscore.js