PDA

View Full Version : Resolved using document.write to write a script tag



traq
11-16-2010, 03:59 AM
Hi,

I need to check if jQuery is loaded on a page, and (if not) write a script tag to load it. I found this (http://forum.jquery.com/topic/cdn-failover-to-domain-provided-js-files) suggestion by John Resig:
<script>
if(typeof jQuery === "undefined"){
document.write('<script src="local/jquery.js"></script>');
}
</script>makes sense. And, looking at the discussion, it seems that it works for others.

However, when I run it, I get this as the page output:
");and a javascript error
unterminated string literal
it seems that the </script> tag - inside the literal string - is being treated as an actual closing script tag, instead of as a string. I've tried switching around double- and single-quotes, to no avail. Any suggestions?

fileserverdirect
11-16-2010, 04:02 AM
Try escaping the characters ala: \<\/\s\c\r\i\p\t\>. Not sure if it work work, but it's worth a shot. If that doesn't work you could use <![CDATA or even "</scr"+"ipt>"

traq
11-16-2010, 04:05 AM
hmm... this works
<script>
if(typeof jQuery === "undefined"){
document.write("<script src='local/jquery.js'></"+"script>")
}
</script>but I think it's stupid. Shouldn't the original version work?

Thought of that while you were typing. I'm trying the <![CDATA[ ]]> idea now
...and now I'm getting ") } ]]> ...

fileserverdirect
11-16-2010, 04:08 AM
hmm... this works
<script>
if(typeof jQuery === "undefined"){
document.write("<script src='local/jquery.js'></"+"script>")
}
</script>but I think it's stupid. Shouldn't the original version work?
No, it shouldn't because the page you are on is rendering HTML, technically anything between <script> </script> is sent for javascript processing. HTML does not know, care, or give a damn if your in a string. Thats why CDATA was invented, and the famous //<!--...

...and now I'm getting ") } ]]> ... try replacing </script> with <\/script>. However NORTON hates that and messes this up. PLEASE SEE THIS THREAD (http://www.webmasterworld.com/forum91/2913.htm)

traq
11-16-2010, 04:28 AM
I suppose that's it, then. good resource, thanks
here's more:
<script type="text/javascript">
<!--//--><![CDATA[//><!--

//JavaScript goes here

//--><!]]>
</script>sheesh...