Pencarian

Rss Posts

 

 

 

JavaScript: Asynchronous Script Loading and Lazy Loading – Federico Cargnelutti

Jul 12, 2011

Most of the time remote scripts are included at the end of an html document, right before the closing body tag. This is because browsers are single threaded and when they encounter a script tag, they halt any other processes until they download and parse the script. By including scripts at the end, you allow the browser to download and render all page elements, style sheets and images without any unnecessary delay. Also, if the browser renders the page before executing any script, you know that all page elements are already available to retrieve.

However, websites like Facebook for example, use a more advanced technique. They include scripts dynamically via DOM methods. This technique, which I?ll briefly explain here, is known as ?Asynchronous Script Loading?.

Lets take a look at the script that Facebook uses to download its JS library:

(function () {
    var e = document.createElement('script');
    e.src = 'http://connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());

When you dynamically append a script to a page, the browser does not halt other processes, so it continues rendering page elements and downloading resources. The best place to put this code is right after the opening body tag. This allows Facebook initialization to happen in parallel with the initialization on the rest of the page.

Facebook also makes non-blocking loading of the script easy to use by providing the fbAsyncInit hook. If this global function is defined, it will be executed when the library is loaded.

window.fbAsyncInit = function () {
    FB.init({
        appId: 'YOUR APP ID',
        status: true,
        cookie: true,
        xfbml: true
    });
};

Once the library has loaded, Facebook checks the value of window.fbAsyncInit.hasRun and if it?s false it makes a call to the fbAsyncInit function:

if (window.fbAsyncInit && !window.fbAsyncInit.hasRun) {
    window.fbAsyncInit.hasRun = true;
    fbAsyncInit();
}

Now, what if you want to load multiple files asynchronously, or you need to include a small amount of code at page load and then download other scripts only when needed? Loading scripts on demand is called ?Lazy Loading?. There are many libraries that exist specifically for this purpose, however, you only need a few lines of JavaScript to do this.

Here is an example:

$L = function (c, d) {
    for (var b = c.length, e = b, f = function () {
            if (!(this.readyState
            		&& this.readyState !== "complete"
            		&& this.readyState !== "loaded")) {
                this.onload = this.onreadystatechange = null;
                --e || d()
            }
        }, g = document.getElementsByTagName("head")[0], i = function (h) {
            var a = document.createElement("script");
            a.async = true;
            a.src = h;
            a.onload = a.onreadystatechange = f;
            g.appendChild(a)
        }; b;) i(c[--b])
};

The best place to put this code is inside the head tag. You can then use the $L function to asynchronously load your scripts on demand. $L takes two arguments: an array (c) and a callback function (d).

var scripts = [];
scripts[0] = 'http://www.google-analytics.com/ga.js';
scripts[1] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js';

$L(scripts, function () {
    console.log("ga and jquery scripts loaded");
});

$L(['http://connect.facebook.net/en_US/all.js'], function () {
    console.log("facebook script loaded");
    window.fbAsyncInit.hasRun = true;
    FB.init({
        appId: 'YOUR APP ID',
        status: true,
        cookie: true,
        xfbml: true
    });
});

You can see this script in action here (right click -> view page source).


Filed under: Design Patterns, Programming, Software Architecture the original (another 826 bytes)

PHP Returning Numeric Values in JSON – Lorna Mitchell

Jul 12, 2011


When I wrote about launching a prototype of a new
joind.in API, quite a few people started to try it out. My friend David Soria Parra emailed me to point out that many of the numbers in the API were being returned as strings. He said:

It’s just a standard problem of PHP REST services. When I try to access it with java I have to convert it over and over again to ints.

I did have a quick look at the PHP manual page for json_encode but I didn’t see anything mentioning this. A few weeks later (my inbox is a black hole and it takes a while to process these things) I fell over a throwaway comment to an undocumented constant JSON_NUMERIC_CHECK, and I added the constant name to my todo list. In the time it took for me to actually get around to googling for this, some wonderful person updated the PHP manual page (this is why I love PHP) to include it as a documented option, and someone else had added a user contributed note about using it.

It turns out, this constant does exactly what I need. Here’s a simple use case:

echo json_encode(array(‘event_id’ => ‘603′));
echo json_encode(array(‘event_id’ => ‘603′), JSON_NUMERIC_CHECK);
?

and the output:

{"event_id":"603"}
{"event_id":603}

There are probably some situations in which you don’t want all your looks-like-a-number data to be returned as a number, but for now it seems to be a good fit for api.joind.in.

PHP color scheme – Henrik Sarvell

Jul 09, 2011

Copyright ? 2011 http://www.prodevtips.com. Visit the original article at http://www.prodevtips.com/2011/07/09/zenburn-for-geany-php-color-scheme/.

Color theming in Geany is quite a no-brainer if you know how to go about it…. Read More

Improved URL auto-linking in Horde – Chuck Hagenbuch

Mar 13, 2011

Horde now uses John Gruber’s regex pattern for matching URLs in text (http://daringfireball.net/2010/07/improved_regex_for_matching_urls).

Using Horde_Xml_Element to quickly generate XML from arrays – Chuck Hagenbuch

Feb 20, 2011

Horde_Xml_Element gives you a quick shortcut for taking PHP arrays and turning them into XML.

Symfony ? subfolders for partials – Anna Filina

Feb 19, 2011

Symfony 1.2 ? 1.4 expects all partials to follow this convention: templates/_partial.php

What happens when you need to organize your partials in subfolder? I tried a number of ?Symfunky? avenues. Feel free to skip to the solution.

Avenues Explored

I first try the call the include_partial helper with ?subfolder/partial?, but that results in Symfony attempting to find the partial in the ?subfolder? module.

Alright, so I try ?module/subfolder/partial?, but that results in Symfony looking for ?_subfolder/partial? because it simply split at the first backslash. I don?t blame the framework developers: I am trying to do something it was not meant to do.

So now I realize that we can set any template from an action using $this->setTemplate(?subfolder/_partial?). Since actions are NOT partials by definition, I decide to use a component. Unfortunately the component doesn?t allow the developer to override templates.

I am starting to feel that the framework mocks me.?So this is how you wanna play it, huh? I will override your sfView class, load it in factories.yml, and there?s nothing you can do about it (insert diabolical laughter)! But then, after almost half an hour, I realize that I?m trying to make it too elegant for something so basic as concatenating a few strings.

Solution

The solution ended up ridiculously simple and does not risk breaking any existing code.

1. Copy get_partial() helper with an extra param: get_partial_subfolder($templateName, $vars = array(), $subfolder)
2. Edit the line that concatenates the file name: $actionName = $subfolder.?/_?.$templateName; (instead of ?_?.$templateName)

There you go, no more headaches. Just remember to use ?echo get_partial()? instead of ?include_partial()? unless you want to override that helper as well. If you are unsure how to create custom helpers, see here under Adding Your Own Helpers: http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer

PHP on Azure and you in Vegas – Michelangelo van Dam

Feb 19, 2011

If you’re developing apps in PHP and you want a challenge that will get you some places, be sure to check out the PHP on Azure contest. Build an app with PHP, deploy it to Windows Azure and participate in a contest with a killer prize: an all-in trip to Las Vegas!

The rules are simple:

  • your app has to be written in PHP
  • preferably own development app
  • use as much as Windows Azure services
  • blog about overcoming this challenge (good/bad/ugly)

A jury will review your app and give you points on implementation, challenge and usage of Windows Azure technologies. But also on how you documented the process of deploying your app to Windows Azure.

Register before February 28, 2011. The contest itself runs from February 1, 2011 until May 15, 2011. If you register quickly, you can get attend a free Windows Azure training course given by Maarten “Mr. Azure” Balliauw on February 22, 2011.

Show the world your skills and participate. Full details of the contest can be found on http://phpazurecontest.com.

If you’re unsure how to start, I’m working on an example application to be deployed anywhere, including Windows Azure.

Flickr: Link Your Photos Back To Your Blog – Stuart Herbert

Feb 12, 2011

I post photos to Flickr from time to time, and then write blog articles about the photos. The blog articles get written days, weeks, sometimes months in advance of when they?re scheduled to appear on my blog ? which makes it a tad difficult to add a link from a photo to all of the blog articles that mention it.

So a couple of weekends ago I knocked up a very crude script that uses the Flickr API (via phpFlickr) to work through all of the published blog posts and make sure each of my Flickr photos has links back to each blog post that mention it. I?m posting it here in the public domain. Hopefully someone will find it a useful starting point to do something similar for their own blog.

<?php

require_once(?phpflickr-3.0/phpFlickr.php?);

$flickrApiKey = ?<your Flickr API key>?;
$flickrSecret = ?<your Flickr API secret>?;
$flickrToken ?= ?<your Flickr auth token>?;

$f = new phpFlickr($flickrApiKey, $flickrSecret);
$f->setToken($flickrToken);
$f->enableCache(?fs?, ?/tmp?, 3600);

// first step ? find the first published blog post
$url = ?http://blog.stuartherbert.com/photography/?;
$rawHtml = file_get_contents($url);
preg_match(?/<h2 id=”post-([0-9]+)”>/?, $rawHtml, $matches);

$blogPosts = array();
$flickrPhotos = array();

$latestPost = $matches[1];
$nextPost = $url . ??p=? . $latestPost;

function updatePhotos($photoIndex, $flickrPhotos,

Truncated by Planet PHP, read more at the original (another 22896 bytes)

Why PHP Namespaces Matter – Matthew Weier O’Phinney

Feb 04, 2011

You’ve heard about PHP namespaces by now. Most likely, you’ve heard about — and
likely participated in — the
bikeshedding surrounding the selection of the namespace separator.

Regardless of your thoughts on the namespace separator, or how namespaces may or
may not work in other languages, I submit to you several reasons for why I think
namespaces in PHP are a positive addition to the language.

Continue reading “Why PHP Namespaces Matter”

Web2project v2.2 Release Notes – Keith Casey

Dec 21, 2010

web2project homepageAs of 19 December 2010, web2project v2.2 is officially live! You can download it from SourceForge now.

While in many releases we might focus on cleanup or functionality or developer aspects or similar, this one is a mishmash of a bunch of useful updates on numerous fronts. This isn’t all of the updates but a bunch of the important ones:

For the Project Managers:

  • We reworked much of the Gantt Chart logic. We’ve added a few icons to better represent the status of tasks and milestones. To make the overall charts easier to understand, we’ve added a legend and shaded alternate lines.
  • Gantt Charts are now exportable as single-page PDFs. You can print, email, share, or whatever with just a click.
  • We updated Token Tasks – which represent Subprojects – have been updated to prevent direct editing. Further, more of the Subproject data synchronizes as expected.
  • Depedency Tracking is now ON by default. This will provide better cascading updates when Tasks move.

For System Admins:

  • If System Timezone or System Admin Email are not set, the system will provide warning messages with links to the specific fields in the System Admin screens.
  • If filesystem permissions are properly configured, the Module screen supports direct uploading.
  • The Reports module has a permissions check applied. Previously, it did not.. though the underlying data was filtered appropriately.
  • The core system supports configurable pagination for the Project List screen and a few others.

For Developers:

  • We replaced our old Javascript library (Mootools) with jQuery. It’s faster, easier to use, and widely supported.
  • Added approximately 40 Unit Tests covering areas such as CDate and other classes.
  • Added a call in the Calendar Module to display arbitrary date-related information. A reference implementation is coming in the next release.

For General Users:

  • We’ve added Czech and Russian translations. If the dice rolls work out, we’ll move to Kamchatka next.
  • We’ve set the field focus to the first text box on each screen.
  • Private Tasks are now respected on all screens including Gantt Charts.
  • We fixed a number of visual issues.

Finally, special thanks goes to community member Opto who consistently submits great bug reports, shares useful patches, and provides random insights that help and speed things along. Thanks!

And that wraps our releases for 2010.

This year we managed 1 Major Release, 3 Minor Releases, and 1 Patch Release. Most of the releases were a week or two later than we wanted but we managed to get all of them out on schedule. More importantly, each and every release has managed to provide new functionality and close bugs while collecting and responding to community feedback.

And in case you missed our recent coverage on SourceForge, check it out!