Javascript page structure

JavaScript code inside HTML tags.

JavaScript is a client side code runs by the user’s web browser.

How to add JavaScript code to our HTML pages?

As we are keeping our JavaScript code inside html pages by using tag, it is upto us to keep our code in any location. However if we want our code to work as soon as the page loads, then we have to keep our JavaScript code inside tag. Here is an sample of simple JavaScript code kept inside head tag.

       This is body content 

The above code will write Hello World as soon as the page loads to the client browser. We can keep the script inside our body tag also . Like this

    This is body content   
   function start() This is body content 

You can see above code will not display the alert message because we have kept the message inside a function and we need to call the function. To call the function onload we have to use the body tag like this.

plus2net.com

Источник

Can I write a tag inside a tag

The usual script tag (type text/javascript) is used to embed js inside markup. The tag itself is not valid js, so you cannot nest script tags (unless it’s in an opaque context, such as a string).

4 Answers 4

  

Explanation [update]:

When you use a HTML tag inside a quoted (literal) string, the tag is treated as a closing tag rather than as a portion of the string. So you cannot directly use the tag inside a script section.

One work-around is to escape the tags and/or split up the

I forced write a SRC atribute into SCRIPT tag, is a similar mode for write a SCRIPT tag into a SCRIPT tag. This script forced to reload a JS file every moment than load a page, prevent cache with use version ramdom number into url. Work fine, load a JS file ok:

 

Источник

Using 'javascript:' inside html tag

I know that if I use 'javascript:' inside a HTML tag. then it can execute javascript code. but it did not work when I checked it on my browser. Or should I use DOM to do this?

You can only use the javascript. inside event handlers e.g. . if you are trying to set the tags ID attribute this way, it isn't going to work. Perhaps you should state what you are trying to do, there may be a better way.

3 Answers 3

You can use javascript: in a href. Like so

@xiaofo unfortunately not. The ID attribute is an anchor, which is very useful when you want the page to jump somewhere.

There are 3 ways to do what you are asking:

  1. Using a single page application like angular, reacts .
  2. Use your own custom design pattern that will replace whatever you want to replace
var global = this; global.id1 = 10; global.id2 = 30; document.querySelectorAll("*").forEach(function(dom) < [. dom.attributes].forEach(function(attr) < if (attr.value.startsWith("javascript:")) < dom.setAttribute(attr.name, global[attr.value.replace("javascript:", "")]); >>); >);
document.getElementById("1").id = "10"; document.getElementById("2").id = "20";

If you are creating a big app then I would reccomand using a single page application (though it might take some time getting to know how it works if you are familiar with it).

If you are feeling adventurous or don't want to bother learning or using an SPA you could create your own framework/design pattern.

If the example you have shown is not a common occurence (and you don't expect it to be more common in the future), easiest solution would be to just manually update the dom.

Источник

Javascript - include another script by using the tag?

So I have a function that writes a string into a div. The string is declared as content, which consists of html code, like this:

This is a test result

example_content = '

some text some text some text some text some text

' + '

some more text.

' + '
' + '

End of text

';

This is a test result

some text some text some text some text some text

some more text.


End of Text

This is a test result/h2>   

Is there a way to avoid writting the script tag as a string ? but as an actual script ? Thanks for any help in advance 🙂

4 Answers 4

You can't do that. You can't add script tags and execute them by writing the HTML. If you must load scripts dynamically, you should add them to the DOM. You can try this to load an external script file and execute the method.

(function(document) < var s = document.createElement('script'); s.id = "external_content"; s.async = true; s.src = "example_content.js"; document.getElementsByTagName('head')[0].appendChild(s); s.onload = function() < document.write(example_content); >>(document)); 

What it basically does is that it creates a new script element dynamically and adds it to the DOM. It also sets an onload event handler which would fire once the script is downloaded completely.

Ok, so the script is being added the DOM, but its being added at the bottom, meaning AFTER the script that needs to access it. Any chance, it can be placed at a particular slot ? Or even at the top ? since it doesnt depend on any other script

@ZyykSavvins What you can do is queue up other scripts that depend on this one in the onload event. But I wouldn't recommend that since it would take forever to load. A better option would be to just create a flag variable and set it to true in the onload event handler. Then you can check for the flag at any dependant script and if its still not set, you set a timeout and recall the script after a second or two.

I'm not sure about this question due to the wording however you don't need two from the html file.

Also if this is what you want I would recommend you use object.innerHTML rather than document.write and place the script at the bottom of your page.

if this doesn't work or isn't what you want please put a comment and I'll remove and use JSLint for an example.

Thanks for the answer. I know my question is a bit vague. I tried to move the document.write inside the file, but still. I'm trying to write

Okay so basically you want to write HTML inside the contents of your div. Say you have a div with the following id: myContentDiv

 /** * NOTICE HOW IM USING \ before " TO ESCAPE THE CHARACTERS INSIDE THE HTML STRING */ var yourCustomHTMLString = "

this is a tag

Also, in your mark-up you need to specify a trigger for your JS, for instance an onload trigger.

And now say you want a function that will load an HTML string into a div.

function loadContent(HTMLstring, targetDivID)

If you are trying to include a JS script inside another JS script, you need Ajax. If you are using a JS library, all common ones have a script load method predefined.

The div would not have yet been created, so I can't really address it with its id. What I have is an object that contains the HTML string and another Object that uses that string to write it in another div. Sounds complicated I know, its just how my current project is built.

What happens first? I would assume you generate the divs at JS level and then you want to write into them. Is that correct? If there is the only event that causes the flow is the onload, then why do you need those two? High level JS libraries(like Google Closure), have methods like goog.dom.createDom. What that does is create a domElement with all the properties and text you want. So instead of first creating the divs and then populating them with content, do everything at once. Don't see why not, unless there is an event which has to trigger all this(such as a mouse click etc)

Its like this: I have an Object, called Frame, that creates and controls a div on screen that acts similar to a window (can be dragged, resized, maximized, closed, etc . ) Then I have an Object called App, which is used to be extended into sub classes. Now, each sub class creates the contents of the Window Object. So the div for the window content is being created inside the same string where the

If I understand you correctly, you insert your content as innerHTML into a , and the scripts don't execute.

As far as I know, this is the expected behavior, as there is no onLoad, document.ready etc. event when you alter the innerHTML of an element.

You could parse the inserted string for nodes. Warning, this is a very "hacky" thing to do, usually there are better ways, for example using the success callback of the ajax functions of the various script libraries.

Nevertheless, here is what we used once. This needs to be executed after you inserted your content string. Please don't judge me, I was young and the time was short.

var div = document.getElementById("yourParentDiv"); if(div != null) < var x = div.getElementsByTagName("script"); for(var i=0;i> 

Источник

Читайте также:  Javascript add class method
Оцените статью