Interesting javascript code in configuration options in MathJax - javascript

As far as I know the javascript code can be "defined" as file
<script type="text/javascript" src="script.js"></script>
or as inline code
<script type="text/javascript">
....
// some more code
....
</script>
So, how this is done ? Nevertheless this is javascript code !?!
<script type="text/javascript" src="MathJax.js">
MathJax.Hub.Config({
extensions: ["tex2jax.js", "mml2jax.js"],
jax: ["input/Tex", "input/MathML", "output/HTML-CSS"]
});
</script>
Video configuring MathJax

(Found out from looking at MathJax demos with Chrome's developer tools)
It's programmatically creating new <script> tags and places them inside the <head> tag, rather like http://requirejs.org/ or http://headjs.com/ does.
Something along the lines of
var scr = document.createElement('script');
scr.setAttribute('src', 'path/to/script.js');
headDOMnode.appendChild(src); // 'path/to/script.js' starts to load..
happens when MathJax.Hub.Config() executes.
Edit: head.js and require.js does it with rather a lot more bells and whistles, of course.

This is just some invalid markup. Excerpt from specs follows (note the usage of must rather than should):
If the src attribute is not set, user
agents must interpret the contents of
the element as the script. If the src
has a URI value, user agents must
ignore the element's contents and
retrieve the script via the URI.

Related

How to combine inline JavaScripts into one?

I'm fixing up a template we're using on one of our sites which has the following code
This snippet works.
<script type="text/javascript" src="http://partner.googleadservices.com/gampad/google_service.js"></script>
<script type="text/javascript">
GS_googleAddAdSenseService("ca-pub-123");
GS_googleEnableAllServices();
</script>
<script type="text/javascript">
GA_googleAddSlot("ca-pub-123", "Foo");
GA_googleAddSlot("ca-pub-123", "Bar");
</script>
<script type="text/javascript">
GA_googleFetchAds();
</script>
I've tried concatenating the static scripts like this
<script type="text/javascript" src="http://partner.googleadservices.com/gampad/google_service.js"></script>
<script type="text/javascript">
GS_googleAddAdSenseService("ca-pub-123");
GS_googleEnableAllServices();
GA_googleAddSlot("ca-pub-123", "Foo");
GA_googleAddSlot("ca-pub-123", "Bar");
GA_googleFetchAds();
</script>
However, now I'm getting an error
Uncaught ReferenceError: GA_googleAddSlot is not defined
I'm no noob when it comes to JavaScript stuff, but I can't imagine why combining the 3 inline scripts into a single <script> tag would make any difference here.
Any ideas?
google_service.js does not define GA_googleAdSlot, but it defines GS_googleEnableAllServices. When GS_googleEnableAllServices is called, it uses document.write to insert a new script element which loads a definition of GA_googleAdSlot. The new script element is inserted in the document after the end of the script element currently being executed. It's complicated, but it's your answer.
Check this out:
https://support.google.com/dfp_sb/answer/112649?hl=en
This is the piece of the document support:
DFP Small Business requires distinct blocks of JavaScript, described below. Do not combine JavaScript blocks, or your code may break.
They have clearly mentioned that you should not combine Javascript blocks!
I am not sure why, but as long as it is mentioned in the document, you have to follow the rules.

How to detect whether a plugin or script has already been loaded without using eval() or requireJS?

I'm working on a plugin that allows to inject 3rd party code into a page (either as iframe or directly into the DOM).
My problem is "direct injections", because I need to make sure, I don't add any <scripts> additional times, if they are needed in my main page and in a page I'm loading and injecting.
For example (and I can't use requireJS), my page.html looks like this:
<html>
<head>
<script type="text/js" src="jquery.js"></script> // exports window.$
<script type="text/js" src="foo.js"></script> // exports window.foo
</head>
<body>
<!-- things that make foo load anotherPage.html and append its content here -->
</body>
</html>
with anotherPage.html
<html>
<head>
<script type="text/js" src="foo.js"></script> // exports window.foo
</head>
<body>
<!-- stuff that also runs on FOO -->
</body>
</html>
Page loading is done via Ajax and when I'm processing the data returned by my request for anotherPage.html I end up with a list of all elements after doing this:
cleanedString = ajaxResponseData
.replace(priv.removeJSComments, "")
.replace(priv.removeHTMLComments,"")
.replace(priv.removeLineBreaks, "")
.replace(priv.removeWhiteSpace, " ")
.replace(priv.removeWhiteSpaceBetweenElements, "><");
// this will return a list with head and body elements
// e.g. [meta, title, link, p, div, script.foo]
content = $.parseHTML(cleanedString, true);
// insert into DOM
someTarget.append(content);
This is where I'm stuck trying to detect whether a script I'm about to append to the document is already there.
I cannot go by the src, because the filename may differ and a script may be hosted on a different domain (with Access-Control-Allow-Origin correctly set). I also don't know, what and if the script I'm about to append returns a global I already have defined and I can't/don't want to use eval() to find out.
Question:
Is there any way to identify whether a plugin or script that may return a global is already "on" a page, when I only have the "non-appended" <script> element available?
Thanks!
here is an example of my self-enclosed module pattern, i call it a "Sentinel":
(function wait(){
if(!self.$){
if(!wait.waitingJQ){
wait.waitingJQ=true;
addScriptTag(JQUERY_URL);
}
return setTimeout(wait, 44);
}
doStuffThatNeedsJquery();
}());
The sentinel pattern work from anywhere (internal or external), doesn't care about script loading order, and works with ANY script loading library. you can list additional depends below the jQuery fork in the same manner, just put your greedy code at the bottom of the sentinel wrapper function.

Having Script within a Script Src tag? <script> (JavaScript etc)

Why does this not work?
<script type="text/javascript" src="//cdn.com/assets/js/jquery.js">
alert("Hello World!");
</script>
But this does?
<script type="text/javascript" src="//cdn.com/assets/js/jquery.js"></script>
<script type="text/javascript">
alert("Hello World!");
</script>
This is general across many HTML tags that pull from source. Micro optimization is important in my situation and I am also curious.
From w3.org (emphasis mine):
If the src has a URI value, user agents must ignore the element's
contents and retrieve the script via the URI.
from http://javascript.crockford.com/script.html:
"If the src attribute is not present, then the content text between the <script> and the </script> is compiled and executed."
As there is a src attribute, the content is not executed
In the first example you define the src which makes it IGNORE the contents of the <script></script>
In the 2nd example you have 2 separate <script></script> tags, the 2nd of which is housing your code to execute.

How to make an external javascript file knows its own host?

Is there any way that in an external javascript file, can know the host of the file?
For example, if I have the site http://hostOne.com/index.php, the code of the file index.php:
<html>
<head>
<script type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
I need that in the file test.js can know the host http://hostTwo.com.
Thank you.
EDIT
or it can know the tag "script" which was called?, with this option I can analyzes the tag and get the "src" attribute. But I don't want to depend on the name of the file test.js and analyze all the tag script that contains the site.
*Solution based on the code of #Armi *
Html:
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script id="idscript" type="text/javascript" src="http://hostTwo.com/script/test.js"></script>
</head>
<body>
<div>...</div>
</body>
</html>
code in JS
var
url = $('head').find('#idscript').attr('src'),
host = url.replace(/(\/\/.*?\/).*/g, '$1');
console.log(host);
I've got an idea (the snippet based on jQuery):
var yourScriptTag = $('head').find('script[src$="jquery-1.7.1.js"]').eq(0);
var theHostnameOfYourScript = $(yourScriptTag).attr('src').replace(/(http:\/\/.*?\/).*/g, '$1');
alert(theHostnameOfYourScript);
jsfiddle example: http://alpha.jsfiddle.net/XsJn8/
If you know the filename of your script (and if this is always the same and unique) you can use this snippet to get the hostname.
If this path is relative (and contains no host) you can get the hostname with a simple location.hostname
Sorry, not possible. The content of the script is downloaded and after this it is fired. At this point the script "thinks" he is at your site.
Of course unless the host is hardcoded in the script.
This is not possible, because the JavaScript code is executed client-sided. You could propably parse it somehow out of your URL but, I don't think either that this is very useful and possible.
Inside test.js, you can use :
var url = document.URL;
then parse the url result.
You can't make cross-site scripting, so if you need more sophisticated stuff, you could write your javascript in php and call :
<script type="text/javascript" src="http://hostTwo.com/script/test.php"></script>
But that's not standard.
Anyway,, the solution is on the server, with a designed proxy.

Using <script> inside a jQuery-template

I'm using jQuery-templates for the first time, and I need my template to include some javascript, so it it run when the template is rendered.
I need at timestamp for the current time...
Writing
<script type="text/javascript"></script>
in a template, renders it to fail.
Is this simply not possible?
the following was blatantly copied from my answer to another question
When the HTML parser finds <script> it will start parsing the contents until it finds </script> which is present in:
document.write("<script src='links7.js?'+Math.random()+></script>
As such, you'll need to change the source so that it's not parsed as the end of a script element:
document.write("<script src='links7.js?'+Math.random()+></scri" + "pt>");
Ideally, you'd have HTML escaped all your inline JavaScript code, which would also mitigate this issue:
document.write("<script src='links7.js?'+Math.random()+></script&
For your particular case (which is different enough for me to not mark as a dupe), make sure that your content between your script tags is HTML escaped, or correctly placed between <![CDATA[ ]]> tags.
<script type="text/javascript"></script>
-or-
/* <![CDATA[ */
<script type="text/javascript"></script>
/* ]]> */
That all being said, you should be calling the necessary JS during the rendering process, and not injecting a script element into the DOM unnecessarily.

Categories