Setting up dependencies with head.js - javascript

I just started using head.js for loading JS files asynchronously with dependencies.
Looking at the API documentation and examples, I see that you can apply labels to JS files, then run some conditions when they are loaded, heres an example in their documentation:
// same as above, but pass files in as an Array
head.load([
{ label1: "file1.js" },
{ label2: "file2.js" }],
function() {
// do something
});
// Labels are usually used in conjuntion with: head.ready()
head.ready("label1", function() {
// do something
});
So basically, that will execute anything in the 2nd block of code (inside the closure), when the file1.js is loaded.
What I wanted to do, is load more files (asynchronously) when other files are loaded..
For example..
First, load the jquery file: jquery.min.ks
After thats successfully loaded, asynchronously load DataTables files: [ dataTables.searchHighlight.min.js, dataTables.conditionalPaging.js, jquery.dataTables.yadcf.js ]
After that, load the main application files: [ myapp_core.js, myapp_whatever.js ]
Heres the code I have now, using head.js, It seems to work ok, but it just doesn't seem right (Having to throw head.load() inside other functions)
// Step #1
head.load(
// First, load the main JS library
[
{ jquery_core: "/include/plugins/jquery-1.11.3/jquery-1.11.3.min.js" },
{ jquery_ui: "/include/plugins/jquery-ui-1.10.4/ui/minified/jquery-ui.min.js" }
],
function() {
console.debug('Loaded jQuery library files, loading jQuery plugin files..');
jquery_plugins();
}
);
// Step #2
function jquery_plugins() {
head.load([
// Load all the jQuery plugin files
"/include/plugins/bootstrap-3.2.0/js/bootstrap.min.js",
"/include/plugins/select2/select2.js",
"/include/plugins/bootstrap3-editable/js/bootstrap-editable.min.js",
"/include/plugins/bootstrap3-editable/inputs-ext/address/address.js",
"/include/plugins/bootstrap3-editable/inputs-ext/typeaheadjs/lib/typeahead.js",
"/include/plugins/bootstrap3-editable/inputs-ext/typeaheadjs/typeaheadjs.js",
"/include/plugins/bootstrap3-editable/inputs-ext/wysihtml5/wysihtml5.js",
"/include/plugins/mustache/mustache.js",
"/include/plugins/slimscroll/jquery.slimscroll.min.js",
"/include/plugins/jquery-cookie/jquery.cookie.js",
"/include/plugins/gritter/js/jquery.gritter.js",
"/include/plugins/jquery-tooltipster-master/js/jquery.tooltipster.js",
"/include/plugins/bootstrap-wizard/js/bwizard.js",
"/include/js/apps.js",
"/include/js/enhanced-select.jquery.min.js",
"/include/js/jquery.multi-select.js",
"/include/plugins/intro/intro.js",
"/include/plugins/switchery/switchery.min.js",
"/include/js/jquery.multiselect.js",
"/include/plugins/parsley/src/parsley.js",
"/include/plugins/parsley/src/extra/validator/APPcustom.js",
"/include/plugins/parsley/src/extra/plugin/parsley.remote.js",
"/include/plugins/bootstrap3-timepicker2/js/bootstrap-timepicker.js",
"/include/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.js",
"/include/plugins/SamWM/numeric/jquery.numeric.min.js",
"/include/plugins/moment/moment.min.js",
"/include/plugins/flot/jquery.flot.min.js",
"/include/plugins/flot/jquery.flot.time.min.js",
"/include/plugins/flot/jquery.flot.resize.min.js",
"/include/plugins/flot/jquery.flot.pie.min.js",
"/include/plugins/flot/jquery.flot.stack.min.js",
"/include/plugins/flot/jquery.flot.crosshair.min.js",
"/include/plugins/flot/jquery.flot.categories.js",
"/include/plugins/sparkline/jquery.sparkline.js",
"/include/plugins/bootstrap-tagsinput/bootstrap-tagsinput.min.js",
"/include/plugins/bootstrap-tagsinput/bootstrap-tagsinput-typeahead.js",
"/include/plugins/jquery-tag-it/js/tag-it.min.js",
"/include/plugins/bootstrap-select/bootstrap-select.min.js",
"/include/plugins/contextMenu/src/jquery.ui.position.js",
"/include/plugins/contextMenu/src/jquery.contextMenu.js",
"/include/js/jquery.mask.min.js",
"/include/plugins/jquery-jstree/dist/jstree.min.js",
"/include/plugins/jquery.expander.js",
"/include/plugins/jquery-labelauty/source/jquery-labelauty.js",
"/include/plugins/jquery-file-upload/js/vendor/jquery.ui.widget.js",
"/include/plugins/jquery-jscroll/jquery.jscroll.js",
"/include/js/modernizr.js",
"/include/plugins/jquery-messi/dist/messi.js",
"/include/plugins/jquery-tmpl/jquery.tmpl.min.js",
{ jquery_highlight: "/include/plugins/jquery-searchhighlight/jquery.highlight.js" },
{ datatables_core: "/include/plugins/DataTables/minify/datatables.min.js" },
{ datatables_searchHighlight: "/include/plugins/DataTables-Plugins/features/searchHighlight/dataTables.searchHighlight.min.js" },
{ datatables_conditionalPaging: "/include/plugins/DataTables-Plugins/features/conditionalPaging/dataTables.conditionalPaging.js" },
{ datatables_ellipsis: "/include/plugins/DataTables-Plugins/dataRender/ellipsis.js" },
{ datatables_yadcf: "/include/plugins/yadcf-0.8.8/jquery.dataTables.yadcf.js" },
{ ckeditor: "/include/plugins/ckeditor/ckeditor.js" }
],
function() {
console.log('All jQuery plugins loaded, loading APP js files...');
APP_js_files();
});
}
// Step #3
function APP_js_files(){
head.load([
// Load the application JS files
{ APP_plugins: "/include/js/APP_plugin.js" },
{ APP_intro: "/include/js/APP_intro.js" },
{ APP_app: "/include/js/APP_app.js" },
{ APP_confirmation: "/include/js/APP_confirmation.js" }
],
function() {
"use strict";
console.log('Successfully loaded all APP js files!');
$.ajaxSetup({
cache:false
});
App.init();
template.init();
account.init();
admin.init();
assets.init();
forms.init();
});
}
The above code is inside init.js, which is loaded via..
<script type="text/javascript" src="/include/js/head.min.js" data-headjs-load="/include/js/init.js"></script>
Is this the right way to do it? The documentation on head.js is pretty limited.
Thanks

Current implementation don't support query or ordering of loading, as I can sas in source code, that's why your solution of the problem is one of the best.

Related

Inline Js with Vue-Meta In Nuxt.js

Basically, Im using Nuxt 2.9.2, and trying to using innerHTML method to inline a Google Optimize script, but whenever i run npm run generate, the code transforms certain aspects even though __dangerouslyDisableSanitizers is whitelisting innerHTML..
This is my Script in Nuxt Config head object
script: [
{
innerHTML: `(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;})(window,document.documentElement,'async-hide','dataLayer', 500 , ${JSON.stringify(
{ [process.env.GOOGLE_OPTIMIZE_ID]: true }
)})`
}
],
__dangerouslyDisableSanitizers: ['innerHTML']
},
Which renders out as the below, tried multiple different ways. could not get it to inline as expected
!function(e,n,t,a,c,s,d){n.className+=" "+t,s.start=1*new Date,s.end=d=function(){n.className=n.className.replace(RegExp(" ?"+t),"")},(e[a]=e[a]||[]).hide=s,setTimeout(function(){d(),s.end=null},500),s.timeout=500}(window,document.documentElement,"async-hide","dataLayer",0,{"GTM-XXXXXX":!0})
should be
(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;})(window,document.documentElement,'async-hide','dataLayer', 500 , 'GTM-XXXXXX'': true }
)})
script: [
{
innerHTML: `window.MY_CONST = 'abcd1234'`,
type: 'text/javascript',
charset: 'utf-8',
},
],
__dangerouslyDisableSanitizers: ['script', 'innerHTML'],

How to integrate mailchimp with nuxt js app?

I'd like to embed the following script into my component in nuxtjs app. But since nuxt has no solution for this. I'd like to ask the vue community to see if there was a better way of embedding external 3rd party js scripts?
Where should I be embedding this type of scipt? And what sort of external configurations do I need to add to enable this to work?
I tried adding directly into my template but it doesn't seem to be working.
<script type="text/javascript" src="//downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"></script><script type="text/javascript">require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us17.list-manage.com","uuid":"XXXXXX","lid":"XXXXXX"}) })</script>
Thanks!
Open up your nuxt.config.js file, and search for the head object. You can add your third party scripts there like this:
// nuxt.config.js
module.exports = {
head: {
title: 'My title',
// etc.
script: [
{ src: "//downloads.mailchimp.com/js/signup-forms/popup/embed.js" },
// You can add multiple third-party scripts here
]
},
// Other stuff
}
Docs: How to use external resources?
I haven't tested it, but I think, since the other part is just javascript, you can add into your page you wan't to show it or a layout file (if you want to show it on multiple pages), like this:
// layout/default.vue
<template>
<!-- Your template -->
</template>
<script>
require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us17.list-manage.com","uuid":"XXXXXX","lid":"XXXXXX"}) });
export default {
// etc...
}
</script>
Although the require part might mess things up...
Let me know if this works!
Insert the MailChimp code inside the <head>
head() {
return {
script: [
{
type: "text/javascript", // mailchimp universal script
src:
"//downloads.mailchimp.com/js/signup-forms/popup/unique-methods/embed.js",
"data-dojo-config": "usePlainJson: true, isDebug: false"
},
{
type: "text/javascript", // mailchimp script for specific popup form
innerHTML: this.getMailchimp
}
],
__dangerouslyDisableSanitizers: ["script"]
};
},
computed: {
getMailchimp() {
if (process.client) {
return JSON.stringify(
window.dojoRequire(["mojo/signup-forms/Loader"], function(L) {
L.start({
baseUrl: "your base url",
uuid: "your uuid",
lid: "your lid",
uniqueMethods: true
});
})
);
}
}
}

How do I use hosted YUI with SSL?

I have downloaded YUI onto my local server and linked through to the yui-min.js. The code i use is:
<script src="//mysite.com/scripts/yui3-3.17.2/build/yui/yui-min.js"></script>
This works fine in a HTTP environment but doesn't work when I switch to HTTPS.
My only bit of yui code is as follows:
<script>
YUI({
classNamePrefix: 'pure'
}).use('gallery-sm-menu', function (Y) {
var horizontalMenu = new Y.Menu({
container : '#demo-horizontal-menu',
sourceNode : '#std-menu-items',
orientation : 'horizontal',
hideOnOutsideClick: false,
hideOnClick : false
});
horizontalMenu.render();
horizontalMenu.show();
});
</script>
I believe i need to use a combo handler to get this to work but i cannot understand the documentation on how this works. Can someone please help?
Thanks!
Matt
That is the complete code that works in https:
<script>
YUI({
classNamePrefix: 'pure',
modules: {
'gallery-sm-menu': {
fullpath: 'js/yui-gallery-master/build/gallery-sm-menu/gallery-sm-menu.js'
},
'gallery-sm-menu-base-min': {
fullpath: 'js/yui-gallery-master/build/gallery-sm-menu-base/gallery-sm-menu-base-min.js'
},
'gallery-sm-menu-templates-min': {
fullpath: 'js/yui-gallery-master/build/gallery-sm-menu-templates/gallery-sm-menu-templates-min.js'
},
'gallery-sm-menu-item-min': {
fullpath: 'js/yui-gallery-master/build/gallery-sm-menu-item/gallery-sm-menu-item-min.js'
}
}
}).use( 'gallery-sm-menu',
'gallery-sm-menu-base-min',
'gallery-sm-menu-templates-min',
'gallery-sm-menu-item-min', function (Y) {
var horizontalMenu = new Y.Menu({
container : '#demo-horizontal-menu',
sourceNode : '#std-menu-items',
orientation : 'horizontal',
hideOnOutsideClick: false,
hideOnClick : false
});
horizontalMenu.render();
horizontalMenu.show();
});
</script>
YUI CDN (yui.yahooapis.com) doesn't support HTTPS endpoint. Gallery modules such as gallery-sm-menu will loads from HTTP CDN as default. You need to define the module within YUI configuration object.
The example as follows. Please see also YUI Global Object.
YUI({
modules: {
gallery-sm-menu: {
fullpath: 'https://your-domain/your/path/to/module.js'
}
}
}).use("gallery-sm-menu", function (Y) {
// do something.
});

Is there an example of setting and retrieving settings from a Rally SDK 2 app?

What does a settings object look like? I can't seem to updateSettings with anything and get something back interesting. I'm printing out this.settings and every time I refresh, it just logs a prototype object with no values.
This is what my test app looks like. I am putting it into a panel inside Rally, not running remotely.
<script type="text/javascript" src="/apps/2.0p2/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function() {
/*global console, Ext */
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
//Write app code here
console.log( "settings", this.settings );
this.updateSettings( { Name: 'test', Value: Ext.JSON.encode( { test: "blah" } ) } );
}
});
Rally.launchApp('CustomApp', {
name: 'test'
});
});
</script>
Turns out there is a bug in the preview version I was using. And I was trying to pass the wrong kind of preference. Note that preferences are scoped to the App ID and not to the project or workspace. Since it needs the app's ID, it doesn't work when run outside Rally.
The bug is that the updateSettings function is missing a line. You can easily override this by adding the same function to your app definition (isn't it neat that the source is included in the docs?) Just make a function like this:
updateSettings: function(options){
Rally.data.PreferenceManager.updateAppPreferences({
appID: this.getContext().get('appID'),
settings: options.settings,
success: function(updatedSettings){
Ext.apply(this.settings, updatedSettings);
if(options.success){
options.success.call(options.scope);
}
},
scope: this
});
}
So, then, the preference object should be passed like this:
this.updateSettings( {settings: { test: "blah" ) } } );
Then, when it comes back, the getSetting("test") will give me "blah". (It creates a preference with Name equal to "test", Value equal to "blah" and an AppId equal to the current app.

Passing bootstrapped variables and JSON to require.js

What is the best practice for passing bootstrapped variables within the rendered page (i.e. JSON data or config variables) to require.js so they can be checked for an used by dependancies?
It looks like this could be done by checking the window object (i.e. window.bootstrapped_models but that does not seem very optimal.
app.html - example data within the HTML document
<script>
var config = {
"isAdmin": true,
"userId": 1
};
var bootstrapped_models = {
"groups": [
{
"id": 1,
"name": "Foo"
},
{
"id": 2,
"name": "Bar"
}
]
}
</script>
app.js - example app using require()
require(['jquery', 'GroupCollection'], function($, GroupCollection) {
// extend default config
if (config) {
$.extend(defaults, config);
}
// use bootstrapped JSON here
var collection = new GroupCollection;
if (bootstrapped_models.groups.length > 0) {
collection.add(bootstrapped_models.groups);
}
});
The answer from #timDunham was helpful, but it felt a little overly complicated to me. Playing around with require.js and Lithium (PHP MVC) I came up with the following. It's simple and has worked in each instance I've run into.
<script type="text/javascript">
define('bootstrapData', function () {
return <?php echo json_encode($bootstrapData) ?>;
});
</script>
Which is then available by doing the following:
define(['bootstrapData'], function(bootstrapData) {
console.log(bootstrapData); // Will output your bootstrapped object
});
Obviously the way I'm bringing the data in is language specific, but the rest should be useful regardless of your situation.
Not sure if my method is best practice but I do something a lot like what you are doing except instead of butting the bootstrapped models on the global object, I create a define for it in my HTML page:
<script type="text/javascript">
define("bootstrappedModelJson", function() {
return #Html.Action("Controller", "RenderModel");
});
require({
baseUrl: //etc.
}, ["app"],
function(){
});
</script>
then I have a js file called current.model that can be required by other modules and looks like this:
define(
[
'require',
'model'
],
function (require, Model)
{
var json= require("bootstrappedModelJson");
return new Model(json);
});
You can solve problems with optimize/build by disabling the bootstrapData in your build.js
Like this:
paths: {
bootstrapData: "empty:",

Categories

Resources