开发者

Are there any reasons for why you would include JavaScript using document.writeln

Are ther开发者_JS百科e any good reasons for why you would include JavaScript like this:

<script type="text/javascript">document.writeln('<script src="http://example.com/javascript/MyJavaScript.js" type="text/javascript"><' + '/script>');</script>

(Sorry for the long scrolling line. This is in the head of a HTML document.)

I've been looking at some HTML recently and I've noticed this a few times (all on the one site). I can't think of any reasons why you would do it like this, but I can hardly claim to be a web developer. It's likely that these lines of code are automatically generated, but still, someone somewhere must have thought this was a good idea.


This technique has been used to load external scripts in parallel, preserving the execution order.

It has some drawbacks, for example, in IE and Opera, even if the scripts are loaded in parallel, other external resources like images, stylesheets, other frames, etc... are blocked from downloading until the scripts are loaded.

But nowadays, I would recommend to include external scripts by DOM scripting, generating dynamically script elements, but you have to care about IE memory leaks.

Check this test page to see the behavior of your browser.


In some cases, the document.writeln method is used to obfuscate the source of the script, and/or break simplistic ad blockers that do simple string matching on the generated html:

document.writeln('<' + 'sc' + 'r' + 'ip' + 't' + etc...)

and

document.writeln('<script src="' + decode_obfuscated_url('encoded garbage here') + '">');


You may need to dynamically include a javascript file based on some sort of client-side business logic.


The site requires the js to be loaded later after some delay or after page is loaded.


I wouldn't say there are any particular reasons. It is just one way of writing directly to the document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜