Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Dynamic loading of javascript files into web pages

Reply
Thread Tools

Dynamic loading of javascript files into web pages

 
 
Jorge
Guest
Posts: n/a
 
      06-26-2009
On Jun 26, 9:24 am, neilc <(E-Mail Removed)> wrote:
> (...)
> There is a discussion here
>
> http://stackoverflow.com/questions/2...amically-load-...
> andhttp://www.artzstudio.com/2008/07/beating-blocking-javascript-asynchr....


And a video here: Steve Souders: "Life's Too Short - Write Fast Code
(part 2)", "Advanced script loading: six ways to load scripts without
blocking the page" (starting @10m40s)
http://www.youtube.com/watch?v=52gL93S3usU

DON'T MISS IT: John Resig's ber-cool "degrading script pattern",
starting @22m15s.

I wonder why jewels like these don't make its way into the resources
FAQ.

> For those who do not get it (ie PointedEars)


--
Jorge.
 
Reply With Quote
 
 
 
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      06-26-2009
Thomas 'PointedEars' Lahn wrote:
> neilc wrote:
>> There is a discussion here
>>
>> http://stackoverflow.com/questions/2...ink-cs-include
>> and
>> http://www.artzstudio.com/2008/07/be...ynchronous-js/

>
> How typical, script-kiddie. You need to refer to work of
> other people because you don't have any arguments yourself.


And, of course, you have selective perception, too:

,-<http://stackoverflow.com/questions/21294/how-do-you-dynamically-load-a-javascript-file-think-cs-include>
|
| I used a much less complicated version recently with jQuery:

jQuery, hm, hm. What was the reason he used jQuery despite considerable
criticism? Cult-like dependency because of cluelessness? I see.

| It worked great in every browser I tested it in: IE6/7, Firefox, Safari,
| Opera.

Extraordinary. Now you need to test all the other browsers out there, dude,
and hope nothing changes about this undocumented feature in the future.

| The technique we use at work is to request the javascript file using an
| AJAX request and then eval() the return. If you're using the prototype
| library, they support this functionality in their Ajax.Request call.

"AJAX request", hm, hm. What if "AJAX" is not supported or disabled?
You don't care for those users? I see.

| i've used yet another solution i found on the net ... this one is under
| creativecommons and it checks if the source was included prior to calling
| the function ...
|
| /** include - including .js files from JS - http://www.velocityreviews.com/forums/(E-Mail Removed) - 2005-02-09
| ** Code licensed under Creative Commons Attribution-ShareAlike License
| ** http://creativecommons.org/licenses/by-sa/2.0/
| **/
| var hIncludes = null;
| function include(sURI)
| {
| if (document.getElementsByTagName)
| {
| if (!hIncludes)
| {
| hIncludes = {};
| var cScripts = document.getElementsByTagName("script");
| for (var i=0,len=cScripts.length; i < len; i++)
| if (cScripts[i].src) hIncludes[cScripts[i].src] = true;
| }
| if (!hIncludes[sURI])
| {
| var oNew = document.createElement("script");
| oNew.type = "text/javascript";
| oNew.src = sURI;
| hIncludes[sURI]=true;
| document.getElementsByTagName("head")[0].appendChild(oNew);
| }
| }
| }

Ridiculous. Not only that it doesn't do as advertised (anybody surprised?),
the whole point of asynchronous loading is that execution continues while
the script is loading. Therefore, the existence of the `script' element
(which is not even tested here!) does not mean anything for the loading
state of the script.

(What might work for detection is declaring a variable at the top of the
script and assigning an identifying value to it at the bottom. We have
discussed this before.)

| Just found out about a great feature in YUI 3 (at the time of writing
| available in preview release). You can easily insert dependencies to
| YUI libraries and to "external" modules (what you are looking for)
| without too much code: YUI Loader.

Which follows the same weak assumption, of course. But then YUI is not
designed to degrade gracefully, to follow accessibility guidelines and
legislation and all.

| all the major javascript libraries like jscript, prototype, YUI have
| support for loading script files.

Let's eat sh*t! A million flies can't be wrong.

,-<news:(E-Mail Removed)>
|
| You've replaced using straightforward, well supported script tags with
| a src attributes by the complex and iffy script above. Even had you
| not reported problems, I would suspect some browsers wouldn't react
| well to what you are doing.

Finally, hear the voice of reason.

,-<http://www.artzstudio.com/2008/07/beating-blocking-javascript-asynchronous-js/>
|
| 5. Vladimir Dzhuvinov tipped... September 15th, 2008 at 1:07 am
|
| Hi,
|
| I don’t know how versed your readership is, but in case there are any
| casual readers, it would be good first to explain to them that browser
| interpreters “block” script execution for a good reason:
|
| http://www.mozilla.org/js/language/j...ion-model.html
|
| 6. Arup stated... October 7th, 2008 at 4:06 am
|
| This implementation has several disavantages also . Like page timeout
| functionality . Sometimes the ojects are set to null and js not works
| on the page .

Even some people there got it.

>> For those who do not get it (ie PointedEars)

>
> *You* don't get it. If you continue loading the document while scripts are
> loading (if that, all of this is based on the weak assumption that scripts
> can be dynamically loaded everywhere), methods that these scripts provide
> may or may not be available while the document is loading.
> [...]
> Then again, when it has become necessary to load scripts dynamically in
> order to create a viable document, maybe, just maybe, there is something
> wrong with the scripts, such as size (for including a lot of unused
> features, or providing them through unnecessarily extensive method
> overloading), or runtime efficiency (for thinking every computer is under
> all conditions as fast as the testing system, and for foolishly thinking it
> would be faster to add a listener to every element in sight instead of event
> delegation)?
>
> And when there are 10 scripts or more in a document, maybe, just maybe,
> somebody has not understood a first thing about browser scripting and Web
> authoring, and just tries to have their tag soup spiced by including a dozen
> script libraries from everywhere, written by equally clueless people?


q.e.d.

BTW, check out loadScript() from <http://PointedEars.de/dhtml.js>, and
notice the copyright date in the JSdoc ...


PointedEars
 
Reply With Quote
 
 
 
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      06-26-2009
neilc wrote:
> Thanks for you response, this is a much better explanation than your
> previous efforts which were rude and unhelpful. I appreciate you
> taking the time to explain. You're tone is a quite uptight and
> childish, you might enjoy life more if you had some therapy ?


*PLONK*
 
Reply With Quote
 
One Dumm Hikk
Guest
Posts: n/a
 
      06-27-2009
On Jun 25, 3:00*pm, Peter Michaux <(E-Mail Removed)> wrote:
> On Jun 25, 11:46*am, Jeremy J Starcher <(E-Mail Removed)> wrote:
>
> > Load four scripts, they load one after another while blocking all other
> > elements on the page fromloadingat the same time. *By making them
> > dynamically declared script elements (either using document.write or
> >dynamicSCRIPT elements), it allows concurrentloadingwith other
> > elements.

>
> I wish Randy Webb was around right now. I've cc'ed him on this
> message. He is/was a fan ofdynamicscript tag insertion at least for
> some purposes.
>
> Peter


You found me. I have no idea why but AOL put the email in my
spam folder and for the first time in almost 2 months I looked
through it. I guess fate had it that I should see it.

Dynamically loading script files to speed up the loading process?
Garbage.

What it will do, if done properly, is speed up the initial
rendering of the page. But it WON'T speed up load time of the
files and will actually slow it down. The reason it will
actually slow it down is because it has to do more work to
load the files. Whether the file is static coded or dynamically
loaded, the file still has to be downloaded from the server.
Want it to download faster? Make the file physically smaller.
Any other advice is magical hocus-pocus for making it load
faster if everything else is the same.

As for the script posted, it won't speed up page rendering
even if you get it to work. Why? It isn't loading the scripts
after the onload event fires, it is trying to dynamically
load them AS the page is loading. No difference than having
them hard coded in script tags.

Aside from some of the problems pointed out already, there
remains an issue of the way you are calling it. Rather than
calling it inline as you are, assign it to the onload event
handler so that the scripts aren't loaded until the onload
event fires. When the onload event fires, the page will render.

function loader() {
var aScripts = [ "scripts/jquery.js",
"scripts/jquery.scrollTomin.js",
"scripts/jquery.localscrollmin.js" ];

for (var i = 0; i < aScripts.length; i++)
{
var p = document.getElementsByTagName( "HEAD" )[0];
var c = document.createElement( "script" );
c.type= "text/javascript";
c.src = aScripts[i];
p.appendChild( c );
}
}
window.onload = loader;

Then, it won't try to load them until the page has loaded
and that will APPEAR to speed up the page loading but it won't.
It will actually slow down total page load time.

Ever wonder why people think JS is so hard? Because they try to
make it harder than it has to be. KISS - Keep It Simple Stupid.

After all this time, I would have thought TL had exited certain
stages of life but I see he hasn't. Sad.
 
Reply With Quote
 
Garrett Smith
Guest
Posts: n/a
 
      06-27-2009
Jorge wrote:
> On Jun 26, 9:24 am, neilc <(E-Mail Removed)> wrote:
>> (...)
>> There is a discussion here
>>
>> http://stackoverflow.com/questions/2...amically-load-...
>> andhttp://www.artzstudio.com/2008/07/beating-blocking-javascript-asynchr...

>
> And a video here: Steve Souders: "Life's Too Short - Write Fast Code
> (part 2)", "Advanced script loading: six ways to load scripts without
> blocking the page" (starting @10m40s)
> http://www.youtube.com/watch?v=52gL93S3usU
>
> DON'T MISS IT: John Resig's ber-cool "degrading script pattern",
> starting @22m15s.
>


Thanks for that link. That is horrible advice and should be avoided.

It was discussed on John Resig's website[0].

> I wonder why jewels like these don't make its way into the resources
> FAQ.
>


Good point. It is worth mentioning that there is a lot of poor advice
provided by experts that should not be followed. The web is horribly
broken. This video serves as an excellent example of an "industry
expert" providing up horrible advice. It should be recommended against
and the section on "John Resig's degrading script tags", which Steve
calls "really really awesome", serves as a fine example of why.

<FAQENTRY>
Q: I saw a video online. Why wasn't it in the FAQ?
A: Video presentations often contain advice that is either
incorrect or inadvisable. It possible, though unlikely, that the video
has not been reviewed and contains accurate and valuable information.
Before posting a request for review, please search the archives for
discussion about the video.
</FAQENTRY>

Steve:
| It turns out, this is really really awesome, but it actually doesn't
| work in any browser. There's no browser that works this way to like
| pay attention to the code in the script blocks if there's a source
| attribute being used.
|
| But it turns out its really easy across all browsers to add that.
| And the way we add that is.. Oh, and this is nice because it's
| cleaner, there's only one script tag instead of two script blocks,
| it's clearer, its very clear that this script code has a dependency
| on menu.js, um, and it's safer. If the external script fails, then,
| ah, the inline code won't be scalled.
|
| But, since it doesn't work in any browser, you have to do a little
| work. And it's not that much work and it's not that complicated, so
| at the end of menu.js, so that's why I renamed it to
| "menu-degrading.js", so at the end of "menu-degrading.js", I basically
| just do this loop:
|
| I get all the script elements, I loop through them, until I find the
| script whose name is "menu jay", "menu-degrading.js" and then I look
| at its innerHMTL property. And that's basically going to be, innerHTML
| is going to be this code, right here (points to example), and I just
| eval it.

None of the three reasons is true. All are blatantly false and in being
false, they serve as reasons for eschewing this technique.

Because a SCRIPT element is not allowed to have HTML, expecting a script
tag to have its text available as innerHTML seems risky. For example:

javascript: alert( document.createElement("script").canHaveHTML)

The "inline code" here is defined as fallback content in HTML 4.01[1].
That means it is only displayed if the script does *not* load. That is
the exact opposite of what this technique requires. Here, Steve is
expecting the fallback content of a script tag to be executed only when
the src is loaded. This works exactly the opposite of the way the HTML
4.01 standard states and this was clearly pointed out on John Resig's
blog[3][4]. It is unreasonable for Steve to have ignored this criticism,
yet he continued to advocate it *after* that fact was pointed out. Steve
Souders is arrogant and not amenable to criticism.

The script's innerHTML is then passed to eval.

The file name changed it's not "menu.js", but now "menu-degrading.js",
but notice how Steve gets that wrong a couple of times. That right there
is evidence that the "degrading" part is unrelated to the original code.

The inline code at the end of menu-degrading.js loops through elements
in the document. It uses all global variables, including a global loop
counter |i|. The eval method is called in global context.

Looping through the DOM while the page loads is a strategy that hurts
performance.

AISB, eval is called in global context. Steve did not mention this, and
the code is so naive that I doubt he is even aware of it, but the code
must exist in global context, or use a separate sandbox function. This
has to do with eval using the scope of the calling context, variable
object, and the this value. If eval is called within a function, then it
will use that function's [[Scope]], variable object, and |this| value.
This can complicate the situation by identifiers being resolved to that
scope chain.

Example:
function doEval(s) {
var i = 10;
eval(s);
alert(i);
}

doEval("i = 20;");

Result:
elerts "20";

I've used the identifier |i| on purpose because it is a common mistake
to forget |var| in initializing a loop variable.

Such issue might not happen on a simple first test. However, if put into
production, it could happen at a later time with different data and
different identifiers. It could potentially causing bugs that might not
arise immediately. If and when they happen in production, it would
severly compromise the security of an application. Inline code often
makes use variables from the server, e.g.:- <%= serverOutput %>, so it
might be a problem that could go unnoticed until, well, it became a
horrible security problem.

Steve mentions in that video that "Doug" remained silent when he
mentioned eval.

Another problem with eval is that when an EvalError occurs, the browser
may not provide information about what was being eval'd that caused the
problem. Instead, the browser will state that eval(s) caused a problem.
Since eval can't be stepped into, it is harder to debug. Indeed, this
is a problem in Dojo that I noticed way back in Dojo 0.4.

Back to Steve's example, that the file "menuteir.js" now has to know
something about the application's performance tricks. That is awful
design and a flagrant violation of SRP. Steve says it is cleaner and
clearer. That is untrue. It is less clear, more complicated because it
requires more code inside menuteir.js to execute the inline script
content. The menuteir.js should not be have knowledge of the performance
tricks used to include it. It severely complicates things; it does not
make things simpler, nor clearer.

It does not make things "safer" either, as I have already explained the
problems with eval.

| If the external script fails, then the inline code won't be called.

That may be true in buggy implementations, but according to the HTML
4.01 specification, the exact opposite is designed to happen. Code
should not rely on specification violations. Utilizing proprietary
(MSIE) extensions is one thing, but expecting every browser to go
against the spec is a very *unsafe* design decision.

Not cleaner, nor clearer, nor safer.

The technique requires implementations to violate the HTML 4 standard.
(According to Steve, this is "all browsers"). It complicates the design
of the code, making it harder to tune and increase likelihood of errors.
For browsers that behave the way Steve wants, Steve's approach impacts
performance by looping through the DOM, and, by using eval, introduces
fragility into the code by eval.

It is really a very poor idea. As Randy said, KISS.

Steve Souders is ignoring valid criticism, disregarding public
standards, and throwing caution to the wind.

I see that Randy and Thomas have their own thoughts on this. The
criticism I provide can tends to annoy the "experts" quite a bit. See
the whatwg list for details. Good to see that I am not alone here.

The part about "depends" in 28:00 is where steve talks about declarative
chaining of script loads. It is another very poor design idea, and it
prompted my proposal for "depends" on script tags on whatwg. That design
idea follows the "I'm Done" paradigm, not "Do This". For more
information on "I'm Done", see H.S. Lahman's explanations on comp.object.

The "Managed XHR" solution also requires eval, and has all the
complications associated with that, just as in Dojo.

Technique 4 Script onload aka "The Best One", shows code that modifies
Host objects with expandos. For reasons that have been discussed here
many times, code which modifies host objects is error prone. According
to Steve, if you use both onload and onreadystatechange, it will work in
"all browsers". Again, this relies on the approach of "Do This" instead
of "I'm Done".

I do agree that this deserves mention in the FAQ. If Steve's book is
going to be included, it ought to mention that his application design
advice is considerably harmful.

Garrett
[0]http://ejohn.org/blog/degrading-script-tags#postcomment
[1]http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.1
[3]http://ejohn.org/blog/degrading-script-tags#comment-319983
[4]http://ejohn.org/blog/degrading-script-tags#comment-320005
--
comp.lang.javascript FAQ: http://jibbering.com/faq/
 
Reply With Quote
 
Gregor Kofler
Guest
Posts: n/a
 
      06-27-2009
One Dumm Hikk meinte:

> Ever wonder why people think JS is so hard? Because they try to
> make it harder than it has to be. KISS - Keep It Simple Stupid.


But then John Resig and his colleagues couldn't fill their blogs with
sparkling new ideas of how to "optimize" code.

As Jorge already mentioned:
http://www.youtube.com/watch?v=52gL93S3usU and the "degrading script
pattern" - it escapes me where the actual problem is, requesting such a
bizarre "solution".

Gregor


--
http://www.gregorkofler.com
http://web.gregorkofler.com - vxJS, a JS lib in progress
 
Reply With Quote
 
Jorge
Guest
Posts: n/a
 
      06-27-2009
Come and see it by yourself:

Parallel script loading SEVERELY cuts scripts loading time:

http://jorgechamorro.com/cljs/068/

--
Jorge.
 
Reply With Quote
 
Jorge
Guest
Posts: n/a
 
      06-27-2009
On Jun 27, 10:42*am, Gregor Kofler <(E-Mail Removed)> wrote:
> (...)
> As Jorge already mentioned:http://www.youtube.com/watch?v=52gL93S3usUand the "degrading script
> pattern" - it escapes me where the actual problem is, requesting such a
> bizarre "solution".


The problem is:

- Given a script that has not been loaded yet (still loading), -
usually a dynamically inserted one-,
- Find the best way to have some piece of code run asap, immediatly
after the script (above) has loaded and executed.

(note that "onload" is not -usually- available on <script> tags in
most browsers)

I think that Resig's idea is great for many reasons. Unless, or until,
somebody else shows me a better way...

--
Jorge.
 
Reply With Quote
 
Jorge
Guest
Posts: n/a
 
      06-27-2009
On Jun 27, 10:01*am, Garrett Smith <(E-Mail Removed)> wrote:
> (...)
> I do agree that this deserves mention in the FAQ. If Steve's book is
> going to be included, it ought to mention that his application design
> advice is considerably harmful.


Mention that *you* consider it harmful.

--
Jorge.
 
Reply With Quote
 
Jorge
Guest
Posts: n/a
 
      06-27-2009
On Jun 27, 3:49 am, One Dumm Hikk <(E-Mail Removed)> wrote:
>
> Dynamically loading script files to speed up the loading process?
> Garbage.
>
> What it will do, if done properly, is speed up the initial
> rendering of the page. But it WON'T speed up load time of the
> files and will actually slow it down. The reason it will
> actually slow it down is because it has to do more work to
> load the files. Whether the file is static coded or dynamically
> loaded, the file still has to be downloaded from the server.
> Want it to download faster? Make the file physically smaller.
> Any other advice is magical hocus-pocus for making it load
> faster if everything else is the same.
> (...)



I'm not sure why do you say so, as it's obvious (isn't it ?) that
latency times add up when the scripts are loaded in series.

And for servers that throttle downloads (more and more each day, e.g.
youtube, me.com...), the time to download n scripts in parallel is not
necessarily === n* the time to download a single one.

--
Jorge.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Using Web.config's <system.web><pages><controls><add /></controls></pages></system.web> To Register UserControls Nathan Sokalski ASP .Net 5 01-10-2007 10:50 AM
Using Web.config's <system.web><pages><controls><add /></controls></pages></system.web> To Register UserControls Nathan Sokalski ASP .Net Web Controls 4 12-21-2006 02:50 AM
Using Web.config's <system.web><pages><controls><add /></controls></pages></system.web> To Register UserControls Nathan Sokalski ASP .Net Building Controls 4 12-21-2006 02:50 AM
Dynamic loading of Web User Controls into a Content/ContentPlaceHo =?Utf-8?B?V291dGVy?= ASP .Net 1 02-25-2006 07:37 PM
Availability of Dynamic Architect - Build advanced dynamic web pages without code! jonjon Javascript 0 10-29-2003 10:10 PM



Advertisments