#StackBounty: Lazy load content of slides inside carousel (content is oEmbeds/iframes)

Bounty: 100

I am loading in ajax a modal/popin with a Bootstrap carousel in which each slide is (not an image as in many question about lazy loading) but an iframe from oEmbed from various social networks (facebook, instagram, twitter, …).

The issue is that when I click the button that laods the modal, ALL the slides content get loaded, that is to say 15 to 20 oembeds(eahc of them loading content tetx, image and and javascript…).

I would like to be clever about it and only “lazy loading” slide by slide or even smarter 3 slides by 3 slides.

I am just also mentioning for the sake of information that I am using scrollMonitor and Hubspot Messenger. But i’d rather use Bootstrap slide events to trigger the apparition/load of each slide or any suggestion you would have.

I’m using ruby on rails as back end language

The url of the oEmbed programmatically change as they are inputed from a Admin Backoffice and change on each Article/page but you’ll find below an example :

Page.html

//button to click to make modal appear
<a class="btn btn-primary" onclick="loadModal()" id="socialStoryModal">
      load modal
</a>

Load Modal with Hubspot Messenger in page.js

function loadModal() {  
      var msg;
      msg = Messenger().post({
        message:  'modal.html.erb',/see below the carousel
        showCloseButton: true,
        hideAfter: false
      }); 
    }

modal.html.erb
= Modal with the carousel and the social embeds (here can be up to 50 of them)

I’ve seen tons of libraries to lazy load images and even sometimes scripts/iframes but they all need to have directly add certain classes I n the block, which is of no help for me as I use oembed above and I have nowhere to put these lazy classes.

I need to make it work with these oEmbeds iframes.


Get this bounty!!!

Fetch GET parameters in JS/jQuery

If you have a URL with some GET parameters as follows:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

and need to get the values of each parameters then below is a nifty piece of code solving your requirement.

JavaScript has nothing built in for handling query string parameters.

You could access location.search, which would give you from the ? character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.

You can then access QueryString.c

System Design Interview Prep Material

System design is a very broad topic. Even a software engineer with many years of working experience at top IT company may not be an expert on system design. If you want to become an expert, you need to read many books, articles, and solve real large scale system design problems. This repository only teaches you to handle the system design interview with a systematic approach in a short time. You can dive into each topic if you have time. Of course, welcome to add your thoughts!

Table of Contents

System Design Interview Tips:

  • Clarify the constraints and identify the user cases Spend a few minutes questioning the interviewer and agreeing on the scope of the system. Remember to make sure you know all the requirements the interviewer didn’t tell your about in the beginning. User cases indicate the main functions of the system, and constraints list the scale of the system such as requests per second, requests types, data written per second, data read per second.
  • High-level architecture design Sketch the important components and the connections between them, but don’t go into some details. Usually, a scalable system includes web server (load balancer), service (service partition), database (master/slave database cluster plug cache).
  • Component design For each component, you need to write the specific APIs for each component. You may need to finish the detailed OOD design for a particular function. You may also need to design the database schema for the database.

Basic Knowledge about System Design:

Here are some articles about system design related topics.

Of course, if you want to dive into system related topics, here is a good collection of reading list about services-engineering, and a good collection of material about distributed systems.

Company Engineering Blogs:

If you are going to have an onsite with a company, you should read their engineering blog.

Products and Systems:

The following papers/articles/slides can help you to understand the general design idea of different real products and systems.

Hot Questions and Reference:

There are some good references for each question. The references here are slides and articles.
Design a CDN network Reference:

Design a Google document system Reference:

Design a random ID generation system Reference:

Design a key-value database Reference:

Design the Facebook news feed function Reference:

Design the Facebook timeline function Reference:

Design a function to return the top k requests during past time interval Reference:

Design an online multiplayer card game Reference:

Design a graph search function Reference:

Design a picture sharing system Reference:

Design a search engine Reference:

Design a recommendition system Reference:

Design a tinyurl system Reference:

Design a garbage collection system Reference:

Design a scalable web crawling system Reference:

Design the Facebook chat function Reference:

Design a trending topic system Reference:

Design a cache system Reference:

Good Books:

Object Oriented Design:

Tips for OOD Interview

Clarify the scenario, write out user cases Use case is a description of sequences of events that, taken together, lead to a system doing something useful. Who is going to use it and how they are going to use it. The system may be very simple or very complicated. Special system requirements such as multi-threading, read or write oriented.
Define objects Map identity to class: one scenario for one class, each core object in this scenario for one class. Consider the relationships among classes: certain class must have unique instance, one object has many other objects (composition), one object is another object (inheritance). Identify attributes for each class: change noun to variable and action to methods. Use design patterns such that it can be reused in multiple applications.

Useful Websites

Original Source

jSoup: Java HTML Parser

jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.

jsoup implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do.

  • scrape and parse HTML from a URL, file, or string
  • find and extract data, using DOM traversal or CSS selectors
  • manipulate the HTML elements, attributes, and text
  • clean user-submitted content against a safe white-list, to prevent XSS attacks
  • output tidy HTML

jsoup is designed to deal with all varieties of HTML found in the wild; from pristine and validating, to invalid tag-soup; jsoup will create a sensible parse tree.

Example

Fetch the Wikipedia homepage, parse it to a DOM, and select the headlines from theIn the news section into a list of Elements (online sample):

Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements newsHeadlines = doc.select("#mp-itn b a");

Open source

jsoup is an open source project distributed under the liberal MIT license. The source code is available at GitHub.

Getting started

  1. Download the jsoup jar (version 1.8.3)
  2. Read the cookbook introduction
  3. Enjoy!

Resources

Color Thief

A script for grabbing the color palette from an image.
Uses JavaScript and the canvas tag to make it happen.

How to use

Get the dominant color from an image

var colorThief = new ColorThief();
colorThief.getColor(sourceImage);
getColor(sourceImage[, quality])
returns {r: num, g: num, b: num}

Build a color palette from an image

In this example, we build an 8 color palette.

var colorThief = new ColorThief();
colorThief.getPalette(sourceImage, 8);
getPalette(sourceImage[, colorCount, quality])
returns [ [num, num, num], [num, num, num], ... ]

Demo More from Original Author

JQuery not working in wordpress

Since WordPress version 2.x, jQuery is a build-in JavaScript library, explicitly include the jQuery library into WordPress is not necessary.

$(document).ready(function(){
  alert('test');
});

the above code will be giving an error in the console of your code:

$ is undefined

In WordPress, the $() syntax is always used by other scripting library, and causing the conflict issue and fail to call the jQuery function. You should use jQuery() instead…

jQuery(document).ready(function(){
  alert('test');
});

Alternatively, you can use noConflict()

$j=jQuery.noConflict();

// Use jQuery via $j(...)
$j(document).ready(function(){
  alert('test');
});

P.S jQuery.noConflict();http://wordpress.org/support/topic/141394

Never use jQuery handy function $() in WordPress plugin. You have to use jQuery() or jQuery.noConflict() to work between jQuery and WordPress.

Source

When and how much to mix technologies for a project?

The main idea behind using a technology is to harness the power of code re-usability and libraries that have already been worked on and trusted to be working and functional with minimal or no issues.

The term “Technology” does not just refer to Java or C++ or JavaScript. It also refers to the frameworks that can be used to suffice some or the other requirements with minimum cost and minimal effort investment. One example can be any Application Development Framework Like Oracle ADF, Pega or Drupal, etc. The framework itself provides functionalities that are most common and also takes cares of the issues that people face while developing an application.

Any application which has to be developed from scratch needs a lot of work just to be useful enough to be used in Production environment. Basic Non-functional requirements such as MVC Architecture, Security safeguards, Application Performance, etc. are the basic and most common features of the application. In addition, Secure Login, User Registration and authentication, role mapping and similar features are also mandatory features of the application.

Most frameworks provide features such as configurable work flows, built in UI Elements, security aspects and many other features. Features such as SQL Escaping, HTML Tag Escaping and MVC Pattern architecture are generally already inbuilt to the framework. The developers can simply configure the workflows, create screens and corner out application logic and then the application is good to go.

But is that enough that we may need??

This the main question that we need to ask when trying to select technologies and try to mix them to achieve the application requirement. The Case study can be a sample B-2-B Application say Business-2-Go (B2G).

Advantage of Techs to be selected:

The B2G can be based on 3 major technology products namely an Identity Management System, an Application Development Framework, and a Content Management Service. The technologies in combination provide the architecture to harness the features out of the box.

The IDM would provide Session Maintenance, Role Mappings, Access Authentications and invalid access handling.

CMS on the other hand takes care of the static content of the application. This technology handles the application content which needs to be configurable but would be changed in very rare scenarios. The main usefulness lies in the fact that the CMS portal can be exposed to the customer admin team as well and be comfortable as the code base will not be touched by the Non Development User.

The ADF constitutes to the application flow of the B2G. All user interactions and other business logic is handled by this technology. The flexibility of the framework helps create applications quickly and more efficiently than the older technologies/frameworks such as J2EE Servlets/JSP or struts and so on.

Further technologies like JavaScript, jQuery, CSS have been used to achieve the look and feel that was decided by the client.

Disadvantages of Techs to be selected:

The disadvantages or rather limitations of the tech or the team using the tech is the one that decides whether the tech can be used or not.

The major factors can be:

  • Cost: The technology that has been perfected and supported may be in most cases be licensed. Thus incurring costs to the budget of the project. The alternative may be using Open Source technologies/frameworks. But there the problem exists of the credibility of the source, issue support and whether documentation is enough or not.
  • Resource Availability: Assuming that the cost barrier of the license has been overcome. Now the major concern is whether the resources for the technology are available or not. If not, then can existing resources be trained or can new resources can be acquired. Again the cost factor is affected in this concern.
  • Technology Limitations: Technologies have limitations in themselves also. The limitation may not be a feature that cannot be achieved, but the effort that may be involved in achieving the feature. A simple example may be a particular look and feel of a B2G. Many of the UI Elements may or may not be achievable with the selected core ADF. Or even if they are achievable, it is after a lot of R&D or with lot of hit and trials. Though this is not something that may rule out the technology itself, but may be enough to include other technologies like jQuery into the picture.
  • Interfacing efforts: While mixing technologies, spots/hooks need to be found where 1 tech may latch on to or may be placed in with the other. For example, jQuery is an Independent Tech and in the selected ADF, generally has an internal client side scripts are functioning on its own end. There may be provisions which execute scripts that achieve the UI functionalities. Similarly the CMS may not have stable out of the box connectors to code layer of the application. Thus interfaces are written to implement make this possible. This effort may also turn out to be a concern for using a tech.

An example of tech selection may be PHP. The technology PHP can also be used for creating a complete application and 99% of the same application can be achieved using PHP frameworks. In fact the cost of the tech is 0 (Open Source) and resource costing would be way lower than those of licensed application framework. But the efforts and timescale needed to achieve all the functionalities required will be humongous. Thus ruling out the tech.

Another concern that can be raised is how much the technologies can be mixed. Surely each of the frameworks will be providing some or the other comfort or a feature. Even if they are published in open source or you may have license available. Does that mean that all technologies should be mixed..??

Interfacing technologies uses effort. It also invokes limitations. An example may be the various attempts to integrate popular front-end framework like AngularJS with Oracle ADF. Oracle ADF is a mainly a Server Side Technology, maintaining all functionalities server side and providing a wide palette of features for an application. AngularJS on the other hand is a completely UI framework. It is completely Client Side Intensive Tech. Both frameworks are completely in the opposite directions. Both are unaware of the other. There are blogs showing way how to integrate both the technologies. But all can point out the issues in the integration. This is a small example, but scaling this, similar issues may be faced and thus may be counted as factors in Tech Selection.

In Conclusion, the trade-offs govern the selections of the technologies to be used in a project. Proper selections must be made in order to plan out the architecture. Improper selection may lead to issues, crashes, late deliveries or redundant costs.

References:

Image: https://www.systrends.com/sites/default/files/banner/appdev_banner2.jpg

Creating a re-organizable list of Items using Drag and Drop in Oracle ADF

Sometimes the requirement is to create a list of UI Items which can be rearranged using Drag and Drop in Oracle ADF, similar to the one in jQuery.

Oracle ADF Drag and Drop doesn’t provide the ability to identify, where the drag object is being dropped in the drag target. Thus we cannot know where to place the dropped element in the list.

here is the solution to the same:
Assumption:
–each element is same and is being iterated in a for loop over a list.
–Here dummy data is being used
Here is the below jsff segment:

<af:forEach var="v" varStatus="vi" begin="0" end="10">
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertAbove}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
    <h:panelGroup styleClass="" id="pg1232">
              <af:outputText value="#{vi.index}" id="ot1"><af:componentDragSource/></af:outputText>
    </h:panelGroup>
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertBelow}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
</af:forEach>

below is the Java Code for the managed bean:

needed imports:

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.datatransfer.DataFlavor;
import oracle.adf.view.rich.datatransfer.Transferable;
import oracle.adf.view.rich.dnd.DnDAction;
import oracle.adf.view.rich.event.DropEvent;

import org.apache.myfaces.trinidad.change.ChangeManager;
import org.apache.myfaces.trinidad.change.MoveChildComponentChange;
import org.apache.myfaces.trinidad.context.RequestContext;

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertBelow(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex + 1, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertAbove(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        //        System.out.println(dropTarget.getParent());
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

this code allows you place rearrange the list of items using drag and drop:

I1
I2
I3
I4
I5
I6
I7
I8

can be converted to by picking up I3 and placing it between I5 and I6 :

I1
I2
I4
I5
I3
I6
I7
I8

How to include a JavaScript file in another JavaScript file

There are two main ways to achieve this:

1 – You can load it with an Ajax call and then use eval.

This is the most straightforward way, but it’s limited to your domain because of the JavaScript safety settings, and using eval is opening the door to bugs and hacks.

2 – Add a script tag with the script URL in the HTML.

This is definitely the best way to go. You can load the script even from a foreign server, and it’s clean as you use the browser parser to evaluate the code. You can put the <script /> tag in the head of the web page, or at the bottom of the body.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance.

It means that if you use these tricks directly, you won’t be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

var js = document.createElement("script");

js.type ="text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);var s =newMySuperObject();Error:MySuperObjectisundefined

Then you reload the page hitting F5. And it works! Confusing…

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

function loadScript(url, callback){// Adding the script tag to the head as suggested beforevar head = document.getElementsByTagName('head')[0];var script = document.createElement('script');
    script.type ='text/javascript';
    script.src = url;// Then bind the event to the callback function.// There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;// Fire the loading
    head.appendChild(script);}

Then you write the code you want to use AFTER the script is loaded in a lambda function:

var myPrettyCode =function(){// Here, do what ever you want};

Then you run all that:

loadScript("my_lovely_script.js", myPrettyCode);

OK, I got it. But it’s a pain to write all this stuff.

Well, in that case, you can use as always the fantastic free jQuery library, which let you do the very same thing in one line:

$.getScript("my_lovely_script.js",function(){

   alert("Script loaded and executed.");// Here you can use anything you defined in the loaded script});

 

Source: StackOverflow Question