What is better in this case, document.createElement or document.write? - javascript

Ok, so I'm making an html5 canvas/javascript game. I'm playing around with the idea of making it available to anyone who wants to put the game on their own website, via one little script snippet that links to an external js file.
Inside the external js file, the whole entire game is included, all I need is to find the best way to create a canvas tag via javascript code.
The external js link:
<script src="http://host.com/game.js"></script>
Here is the single line of canvas code that I need to insert into the document:
<canvas id="canvas" style="display:block;margin:0px auto;" width="600" height="550">Your browser does not support the HTML5 canvas element.</canvas>
1. My first option would be to use..
document.write('<canvas id="canvas" style="display:block;margin:0px auto;" width="600" height="550">Your browser does not support the HTML5 canvas element.</canvas>');
However, document.write is frowned upon from what I understand.
2. My next option is to use..
document.createElement(canvas);
document.setAttribute(.....);
document.appendChild(....);
However, this option means I must include a div or some element with the external js link, so that I can append the canvas to it.
3. My last known option is to use..
document.getElementById('divWrapper').innerHTML('my canvas code');
However, this option also means I must include a div with the external js link, so that I can find the id of the div, and write inside it via innerHTML.
Last tip: People will be able to copy the external js link and paste it on their own website in the body, (it will not be in the head), and if my option requires a div tag with the script link, that is fine. I'm going for the least amount of characters that the person has to copy/paste.
So what option would you recommend? Is there another better way that I didn't mention?

I should probably make this an answer.
If document.write [docs] is called when the HTML is parsed (which seems to be the case), then it's perfectly fine to use it.
I would not write longer HTML code with it, but one line of HTML is ok.
Advantages of document.write: (in this case)
Easier for the user to add to his page (just copy and past).
Advantages of innerHTML:
You could provide the user the option to specify the id of the element to append the canvase to. This increases the flexibility for the user, but requires an additional step.

document.write is deprecated, don't use it.
I'd use innerHTML. Adding one div is totally fine and it gives the people, who insert the game, more control where to insert it.

document.write is not a good idea as it only works when called before the document is completely loaded.
A good idea is to use DOM as it is more x-browser.
var canvas = document.createElement('canvas');
canvas.setAttribute(...);
document.getElementById(...).appendChild(canvas);

PPK had run a test on innerhtml vs dom and here is his finding, http://www.quirksmode.org/dom/innerhtml.html, all votes/praises for innerHTML

Related

JavaScript widget code snippet on image onload

I'm working on a JavaScript widget (I actually have several I'd like to update) and hope to distill the embed code snippet down to just a single <img> tag with JavaScript in the onload attribute. In the past I used a along with an <img> tag. Then I switched to just a <script> tag to make the widget non-blocking. I'm working on the <img> only option for usability reasons. It is easier to copy and paste to move the widget around if you don't have to switch into the source view of the WYSIWYG editor. It is also really nice to have something you can visually see in a WYSIWYG editor.
Here's an example of the current draft of the snippet:
<img id='NotablePAD80' class='NotablePAD' src='//dev.notable.webapp.msu.edu/n.png'
data-section='nathanlounds' onload="(function(d){ var i=d.getElementsByTagName('IMG')[0],
u='https://dev.notable.webapp.msu.edu/n.js',
j=i.previousSibling||i; if(j.src!==u) { var s=d.createElement('SCRIPT');
s.type='text/javascript'; s.src=u; i.parentNode.insertBefore(s,i);}})(document);" />
What is the best way to prevent the widget from executing pre-save in the WYSIWYG? The loading of the widget can't change the DOM within the editor.
My ideas:
Look from the presence of the tinyMCE variable. Don't process
widget if it is defined. TinyMCE is an editor I'd need to be
compatible with. But I'd likely need 'fixes' for other WYSIWYG too.
Examine the DOM and look for properties that are
only present within a WYSIWYG, such as being inside an iframe. But I need the widget to work within iframes.
There are problems with both of those options. TinyMCE may not be defined yet when my widget executes. The image load event gets triggered multiple times for some reason. Ultimately I'd love a solution that would work universally.
Thoughts? Brilliant solutions?
Check if a parent of the image has contentEditable enabled, or if the body of the document is in designMode

Inserting Text Into HTML

What I Want: Very simply I have a C program that generates a variable periodically, I want to be able to display this value on a website.
Restrictions: The webpage is HTML, php does not work, javascript does [I have tried a few javascript solutions but they have all been long, tedious and in the end ineffective] I want it to be able to format the text so that it matches the rest of the webpage. Above all I'd really like to find something simple that works.
Freedoms: I can output the variable from my C program to just about any file type and content that I want, the file is hosted so is available locally to the server or online for the client.
Preferred Solutions: I am currently playing around with the object and iframe tags native to html. They give a nice simple input:
<object height=20 width=75 type='text/plain' border=0 data="URL/filename.txt"></object>
inserts the contents of my file, but it can't be formatted so I am stuck with 12pt Courier font which is not acceptable. Using
<iframe seamless height=20 width=75 scrolling='no' src="URL/filename.htm"></iframe>
and adding my desired font/colour/size etc to the htm file gets me the right text style, but htm has a large amount of white padding around it which I can't seem to get rid of so I have to make my iframe quite large for the text to be displayed, but then it doesn't fit smoothly with other text.
So anyone that can answer one of four questions:
How to remove excess padding from htm
How to format the style of a html object
Is there anything in Java as simple as the php [so apparently it doesn't show php code even when you quote it as code. But basically using echo and get_file_contents to insert the contents of a txt file into a html page]
Propose an alternate solution
Padding and style can be handled by css.
By java I assume you mean javascript - google-ing will help you. Without details of what your server is running and what is dispatching your pages we can't give you an exact answer. You might want something with ajax to keep it updating in the background.
Try googling your question, you'd be surprised how often this helps.
I'm not sure what you're trying to do once you get the variable into your web page, but I think something like the following could be useful.
Create a hidden div on your page
Have your C application write the variable to some file
Use jquery to execute an ajax call to pull that value into the div ( or whatever other container you want to use
using some type of timer, execute the ajax call every X period of time, which will then get your up to date variable
on your main page, have another timer that will then come in to that container, grab your value and then you are free to do what you want with it.
This is all off the top of my head without knowing much about what you're trying to accomplish. If you provide some further details we may be able to help you a little more.
You need AJAX... that's just a fancy buzz-word. It means you can tell JavaScript can get a file from the server without reloading the page and you can insert data from that file into your HTML.
AJAX is made much simpler by using a JavaScript library like jQuery, but it can be done without jQuery. There's a pretty decent Getting Started tutorial at Mozilla Developer Network if you want to do it the hard way, but I really recommend jQuery.
As far as formatting... any formatting... you need to use CSS. Just about everything about the appearance of anything on a web page is controlled by CSS. MDN has a Learn CSS section, too.
load jquery on you main html file
put a div with some id (example id="newvalue")
make you c program to write the output in a file (for example value.html)
on main html page header, after jquery include code add some javascript like
$( document ).ready(function() {
$("#newvalue").load('yoursiteurl/value.html');
});

Get full actual html page source including the frameset

For our functional test automation we use QTP with the Webtest Plugin. I have control over the DOM (but not in an easy manner) and can use VBScript and partially Javascript to find a solution.
Whenever we encounter an error during a test I'd like to capture the full HTML page source at that moment. Later, when we are inspecting the error from our reports, we can see what happened and how the DOM looked like at that moment.
Therefore I look for a posibility to capture this source. Normally I did it with
htmlSource = browser("micClass:=Browser").page("micClass:=Page").Object.documentElement.outerHTML
or
htmlSource = browser("micClass:=Browser").page("micClass:=Page").Object.getElementsByTagName("html")(0).innerHTML
Unfortunately this will only capture the full content of the tag the frameset, and the frames, but not the actual content that is located in the frames. (classic frames here, not IFrames)
Now I'd like a way to capture the full DOM source at real time including the content in the framesets. And I'd like them in the right order and place, just like the source appears in the HTML view of the IE Developer Tool.
Does anyone have an idea how I could manage that?
If you really need to have the frames' source inline in the page's HTML the only way I know of achieving this is build the HTML recursively for each element. This may be a lot of work since for every element you'll have to remove the innerHTML from the outerHTML before going to the child elements (and insert them correctly).
If you can live with the frames' HTML being outside you can use Page.ChildObjects() with a description micclass=Frame and then use the same mechanism you used for the page (frames(i).Object.documentElement.outerHTML).
Note that you'll get all the frames under the page so there's no need to get the child objects of the Frame test objects even if the frames are nested in the DOM.

Executing JS in dynamically loaded content

I've started working on a project that loads all of the different pages content dynamically.
On the surface this seems simple enough, an AJAX call to a script that returns the content that is placed inside a DIV. Except that not only HTML but JS is returned as well. I'm seeing a lot of things like this:-
<img src="spacer.gif" height="1" width="1" onload="SOMEJSHERE"/>
Dotted in the code to execute JS functions. This doesn't provide the kind of HTML/JS code separation I've come to love using JQuery.
I can understand that they don't want to load all the JS and HTML at once, there is an awful lot of it... But this just doesn't feel like the best way.
Some experience and suggestions please?
Lyle
Have a look at the jQuery .live() event. It can apply behaviors (event bindings) to all current and future elements on the page, which match the given selectors.
This means that your newly-loaded HTML need not contain any script. Just make sure the loaded elements have the right selectors (class names and id's).
hey i use "eval" to execute js dynamically.
e.g.
<script>
var strjs = 'function execute(){alert("foobaring");} execute();';
eval(strjs);
</script>
In the end I used the tabs.select option from JQuery UI (which we were using for the ajaxed pages) and executed the appropriate JS as needed.

How to dynamically add a Javascript function (and invoke)

Based on a click event on the page, via ajax I fetch a block of html and script, I am able to take the script element and append it to the head element, however WebKit based browsers are not treating it as script (ie. I cannot invoke a function declared in the appended script).
Using the Chrome Developer Tools I can see that my script node is indeed there, but it shows up differently then a script block that is not added dynamically, a non-dynamic script has a text child element and I cannot figure out a way to duplicate this for the dynamic script.
Any ideas or better ways to be doing this? The driving force is there is potentially a lot of html and script that would never be needed unless a user clicks on a particular tab, in which case the relevant content (and script) would be loaded. Thanks!
You could try using jQuery... it provides a method called .getScript that will load the JavaScript dynamically in the proper way. And it works fine in all well known browsers.
How about calling eval() on the content you receive from the server? Of course, you have to cut off the <script> and </script> parts.
If you're using a library like jQuery just use the built-in methods for doing this.
Otherwise you'd need to append it to the document rather than the head like this:
document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></scr" + "ipt>");
In all honesty, I have no idea why the script tag is cut like that, but a lot of examples do that so there's probably a good reason.
You'll also need to account for the fact that loading the script might take quite a while, so after you've appended this to the body you should set up a timer that checks if the script is loaded. This can be achieved with a simple typeof check on any global variable the script exports.
Or you could just do an eval() on the actual javascript body, but there might be some caveats.
Generally speaking though, I'd leave this kind of thing up to the browser cache and just load the javascript on the page that your tabs are on. Just try not to use any onload events, but rather call whatever initializers you need when the tab is displayed.

Categories

Resources