krux / postscribe

Asynchronously write javascript, even with document.write.
MIT License
986 stars 157 forks source link

Inline, not External, Scripts - how to Use Postscribe for these #457

Closed tomgallagher closed 6 years ago

tomgallagher commented 7 years ago

Hi

I'm struggling with inline code snippets.

So this piece of code won't work:

<div id="mydiv"></div>
<script type="text/javascript">
    postscribe("#mydiv", "<script>if (!window.jQuery) { document.write('<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js\"></script>');  } else { console.log('jquery Loaded'); } <\/script>");
</script>

I'm always hitting invalid or unexpected token errors. The closing script tag in the document write statement throws Postscribe, as it normally does in document.write statements inside script tags.

However this code will work

<div id="mydiv"></div>
<script type="text/javascript">
    postscribe("#mydiv", "<script>if (!window.jQuery) { document.write('<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js\"></scr' + 'ipt>');  } else { console.log('jquery Loaded'); } <\/script>");
</script>

I've tied using escaped hexadecimal and unicode characters but they don't seem to be recognised.

Is there any other, cleaner way of making Postscribe work for inline code snippets? I have tried saving them to local storage and downloading a template script that retrieves the code snippet from storage and then uses eithereval or a function to execute the code string. Not working.

Any help/guidance would be most welcome.

ayxos commented 7 years ago

I think is not a postscribe problem, but a document.write problem.

has to be broken up because otherwise it would end the enclosing block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

https://stackoverflow.com/a/236106/3764994