Vuejs 2: How to include (and run) a script tag javascript file in the DOM dynamically? - html

I am using Vuejs and I need to insert script tags in the DOM dynaically to embed JWPlayer videos in this way:
<body>
<!-- HTML content -->
<script src="//content.jwplatform.com/players/KZVKrkFS-RcvCLj33.js"></script>
<!-- More HTML content -->
<script src="//content.jwplatform.com/players/ANOTHER-ID-ANOTHER-PLAYERID.js"></script>
</body>
I have used without results: v-html directive to render the html tags. As well v-bind:src but neither execute the code. I found this solution but it did not work either: How to add external JS scripts to VueJS Components
I used this solution but the script tags (one for each video) must be inserted in the body (not in head): they should create div tags containers and embed the videos. The problem is that the embeded JWPlayer file contains a document.write() statement. And the browser console says: "A call to document.write() from an asynchronously-loaded external script was ignored."
Is there anyway to achieve this?

The link you provided should work.
You probably just need to wait for the script to load before you can use JWPlayer.
const script = document.createElement('script')
script.onload = () => {
// Now you can use JWPlayer in here
}
script.src = '//content.jwplatform.com/players/MEDIAID-PLAYERID.js'
document.head.appendChild(script)
Also make sure you only do this one time for the first component that requires it, from that point onward JWPlayer will be loaded and you can use it without inserting another script tag.

Related

Proper order for scripts in head of my document [duplicate]

When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <head> section, but placing at the beginning of the <body> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the <body> section as a logical place for <script> tags.
So, where is the right place to put the <script> tags?
(This question references this question, in which it was suggested that JavaScript function calls should be moved from <a> tags to <script> tags. I'm specifically using jQuery, but more general answers are also appropriate.)
Here's what happens when a browser loads a website with a <script> tag on it:
Fetch the HTML page (e.g. index.html)
Begin parsing the HTML
The parser encounters a <script> tag referencing an external script file.
The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
After some time the script is downloaded and subsequently executed.
The parser continues parsing the rest of the HTML document.
Step #4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.
Why does this even happen?
Any script can insert its own HTML via document.write() or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.
However, most JavaScript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:
<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>
JavaScript:
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});
Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded and executed, the parser stops parsing.
Antiquated recommendation
The old approach to solving this problem was to put <script> tags at the bottom of your <body>, because this ensures the parser isn't blocked until the very end.
This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts and stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.
In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.
The modern approach
Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.
async
<script src="path/to/script1.js" async></script>
<script src="path/to/script2.js" async></script>
Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible that script 2 is downloaded and executed before script 1.
According to http://caniuse.com/#feat=script-async, 97.78% of all browsers support this.
defer
<script src="path/to/script1.js" defer></script>
<script src="path/to/script2.js" defer></script>
Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.
Unlike async scripts, defer scripts are only executed after the entire document has been loaded.
(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer)
Conclusion
The current state-of-the-art is to put scripts in the <head> tag and use the async or defer attributes. This allows your scripts to be downloaded ASAP without blocking your browser.
The good thing is that your website should still load correctly on the 2% of browsers that do not support these attributes while speeding up the other 98%.
References
async vs defer attributes
Efficiently load JavaScript with defer and async
Remove Render-Blocking JavaScript
Async, Defer, Modules: A Visual Cheatsheet
Just before the closing body tag, as stated on Put Scripts at the Bottom:
Put Scripts at the Bottom
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
Non-blocking script tags can be placed just about anywhere:
<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
async script will be executed asynchronously as soon as it is available
defer script is executed when the document has finished parsing
async defer script falls back to the defer behavior if async is not supported
Such scripts will be executed asynchronously/after document ready, which means you cannot do this:
<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
* might throw "jQuery is not defined" error
* defer will not work either
-->
Or this:
<script src="document.write(something).js" async></script>
<!--
* might issue "cannot write into document from an asynchronous script" warning
* defer will not work either
-->
Or this:
<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
* might throw "jQuery is not defined" error (no guarantee which script runs first)
* defer will work in sane browsers
-->
Or this:
<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
* might not locate #header (script could fire before parser looks at the next line)
* defer will work in sane browsers
-->
Having said that, asynchronous scripts offer these advantages:
Parallel download of resources:
Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute.
Source order independence:
You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS). Execution order still matters though.
It is possible to circumvent the execution order issues by using external scripts that support callbacks. Many third party JavaScript APIs now support non-blocking execution. Here is an example of loading the Google Maps API asynchronously.
The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document's <body> element so they don't block rendering of the page.
But there are some newer approaches that offer better performance, as described in this other answer of mine about the load time of the Google Analytics JavaScript file:
There are some great slides by Steve Souders (client-side performance expert) about:
Different techniques to load external JavaScript files in parallel
their effect on loading time and page rendering
what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).
The modern approach is using ES6 'module' type scripts.
<script type="module" src="..."></script>
By default, modules are loaded asynchronously and deferred. i.e. you can place them anywhere and they will load in parallel and execute when the page finishes loading.
Further reading:
The differences between a script and a module
The execution of a module being deferred compared to a script(Modules are deferred by default)
Browser Support for ES6 Modules
If you are using jQuery then put the JavaScript code wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.
On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.
<script src="myjs.js"></script>
</body>
The script tag should always be used before the body close or at the bottom in HTML file.
The Page will load with HTML and CSS and later JavaScript will load.
Check this if required:
http://stevesouders.com/hpws/rule-js-bottom.php
The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the HTML in document,
Also loading the JavaScript files externally has its own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.
But modern browsers also support some other optimal ways, like async and defer to load external JavaScript files.
Async and Defer
Normally HTML page execution starts line by line. When an external JavaScript <script> element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution. This normal page execution can be changed using the defer and async attribute.
Defer
When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing, but it will be execute only after full HTML parsing is done.
<script src="/local-js-path/myScript.js" defer></script>
Async
When the async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.
<script src="/local-js-path/myScript.js" async></script>
When to use which attributes
If your script is independent of other scripts and is modular, use async.
If you are loading script1 and script2 with async, both will run
parallelly along with HTML parsing, as soon as they are downloaded
and available.
If your script depends on another script then use defer for both:
When script1 and script2 are loaded in that order with defer, then script1 is guaranteed to execute first,
Then script2 will execute after script1 is fully executed.
Must do this if script2 depends on script1.
If your script is small enough and is depended by another script
of type async then use your script with no attributes and place it above all the async scripts.
Reference: External JavaScript JS File – Advantages, Disadvantages, Syntax, Attributes
It turns out it can be everywhere.
You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).
The most conservative (and widely accepted) answer is "at the bottom just before the ending tag", because then the entire DOM will have been loaded before anything can start executing.
There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.
It depends. If you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it at the top. If your styling is 100% CSS and you have all fallback options for the button actions then you can place it at the bottom.
Or the best thing (if that's not a concern) is you can make a modal loading box, place your JavaScript code at the bottom of your page and make it disappear when the last line of your script gets loaded. This way you can avoid users using actions in your page before the scripts are loaded. And also avoid the improper styling.
Including scripts at the end is mainly used where the content/ styles of the web page is to be shown first.
Including the scripts in the head loads the scripts early and can be used before the loading of the whole web page.
If the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code.
The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or after the </body> close tag, depending on when you want the JavaScript to load.
Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.
However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.
Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.
There are some different techniques, but the most straightforward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.
This naturally requires that the script itself is not needed for the rendering of the page.
For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow, but now at Google).
Script blocks DOM load until it's loaded and executed.
If you place scripts at the end of <body>, all of the DOM has a chance to load and render (the page will "display" faster). <script> will have access to all of those DOM elements.
On the other hand, placing it after the <body> start or above will execute the script (where there still aren't any DOM elements).
You are including jQuery which means you can place it wherever you wish and use .ready().
You can place most of <script> references at the end of <body>.
But if there are active components on your page which are using external scripts, then their dependency (.js files) should come before that (ideally in the head tag).
The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute the JavaScript code.
<script> ... your code here ... </script>
</body>
And if you write in jQuery, the following can be in the head document and it will execute after the document loads:
<script>
$(document).ready(function(){
// Your code here...
});
</script>
If you still care a lot about support and performance in Internet Explorer before version 10, it's best to always make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.
If you don't care too much any more about in Internet Explorer before version 10, you might want to put your scripts in the head of your document and use defer to ensure they only run after your DOM has been loaded (<script type="text/javascript" src="path/to/script1.js" defer></script>). If you still want your code to work in Internet Explorer before version 10, don't forget to wrap your code in a window.onload even, though!
I think it depends on the webpage execution.
If the page that you want to display can not displayed properly without loading JavaScript first then you should include the JavaScript file first.
But if you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from a user's point of view, it would seems like that the page is loading faster.
Always, we have to put scripts before the closing body tag expect some specific scenario.
For Example :
`<html> <body> <script> document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script> </body> </html>`
Prefer to put it before the </body> closing tag.
Why?
As per the official doc: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics#a_hello_world!_example
Note: The reason the instructions (above) place the element
near the bottom of the HTML file is that the browser reads code in the
order it appears in the file.
If the JavaScript loads first and it is supposed to affect the HTML
that hasn't loaded yet, there could be problems. Placing JavaScript
near the bottom of an HTML page is one way to accommodate this
dependency. To learn more about alternative approaches, see Script
loading strategies.

Changing a PHP variable when selecting an option from a select box

Basicly what I want to do is to change the stylesheet when the user selects the one they whant from a select box. To do that there would be a variable called $_SESSION['style']. What's the best way to change the variable when clicking it from the select box? (without clicking a submit button). Is it possible to change the stylesheet without reloading the whole page?
Thanksss! :)
Yes you can dynamically inject a CSS file when the select box is updated.
<select onchange="changecss(this.value);">
...
</select>
<script>
function changecss(value){
//based on the value, pick a style sheet here
var cssname='pick your own css file';
csl=document.createElement('link');
csl.setAttribute('rel','stylesheet');
csl.setAttribute('type','text/css');
csl.setAttribute('href',cssname);
document.getElementsByTagName("head").item(0).appendChild(csl);
}
</script>
Edit:
I have seen code that directly change the src value of the current css inclusion. This doesn't not work in some versions of IE, because the browser is not "notified" of a DOM change, and your page is therefore unaffected. Inserting new CSS node in the DOM works more reliably.
With this Ajax wrapper you can dynamically load the CSS file in one line:
<script src="http://www.antradar.com/nano.js"></script>
<script>
ajxcss(self.cssloader,'newcss.css');
</script>
Since PHP is a server-side language that cannot update the data in the user's browser (no "push"), you need a client-side script for the change of the stylesheet without having to reload the page. Changing the stylesheet is possible with javascript. Because your stylesheet filename is stored in a (server-side) session variable, you've got 2 options:
Render the filename into the site (e.g. by echoing it into the javascript code as a variable), so that it can be used by the client side script.
Use an ajax call from the client side script, to get the filename from a PHP script ("pull"), that ouputs the session variable.
However, this might be too much overhead*. Maybe you should consider hardcoding the stylesheet filename into the javascript.
*) if you are using a javascript framework like jQuery or MooTools such things can be implemented easily...
Edit: I just recognized, that you've got a selectbox of items. In this case you surely want to go with the first option: Create the selectbox via PHP and for example use the filenames of the stylesheets as the values. You can than use javascript to change the stylesheet when a onSelectedIndexChanged happens.

dynamically rendering plain .html page on webmatrix

I'm trying to render a .html webpage using #Renderpage() method in Webmatrix but the .html extension is not supported by the method. I guess the method only supports cshtml extensions. Is there a way I can render html pages dynamically on my site (Webmatrix). I dont want to use an iframe because I'll definitely have issues with my jquery files.
I attempted something i feel is safe yet feels unsafe. I resolved to read the html file and inject it to the DOM manually using:
Array html = null;
var mypage = Server.MapPath(page);
if(File.Exists(mypage)){
html = File.ReadAllLines(mypage);
}
After reading the file.....i injected it to the DOM
<div class="s_content s fontfix left s_content2 downdown">
#foreach (var data in html) {
<text>#Html.Raw(data)</text>
}
</div>
All this runs on compilation time before the page is created for rendering.....I attempted some security measures by attempting to inject server-side C# code in the HTML file but was useless. Makes me feel safe atleast. Is this risky? What is the possible threat to this alternative. i wish i can still have an alternative proper solution from the house. Thanks though.
Assuming #Renderpage() doesn't support HTML files, why don't you try Jquery.load or Ajax. There are lots of tutorials based on dynamic loading of html content.
I do something similar but I don't use #Renderpage or an html file. Instead I am using the "onclick" event and a javascript function which opens a cshtml file. You just put this and the java script function in your main cshtml file in the hmtl section. It will open a file in the current directory called my_window.cshtml when clicked
<a onclick=openWin("my_window",700,850);>Open when clicked</a>
<script type="text/javascript">
function openWin(url, width, height)
{
myWindow=window.open(url,'_blank','width='+width+',height='+height);
myWindow.focus();
}
Hope this helps!

Embedding part of a web site

Suppose I want to embed the latest comic strip of one of my favorite webcomics into my site as a kind of promotion for it. The webcomic has the strip inside of a div with an id, so I figured I can just embed the div in my site, except that I couldn't find any code examples for how to do it (they all show how to embed flash or a whole website).
Can someone please show me (or tell) how it's done?
PS I'd rather not use server side scripting or external services (which is what is often recommended for embedding RSS).
Update - Cross domain request with jQuery (on client side)
Yesterday I was browsing James Padolsey's blog, where he posted a great article, on how to do cross domain request with jQuery, also Chris Heilmann has a nice DEMO.
The principle is to use YQL -> a yahoo api for web page queries, where you receive a JSON with all the html. Happy scraping :)
Scrape remote data with php, load with jQuery
What about considering simple AJAX call, that would intercept the comic element and update with its contents your <div id="update-comic" /> primarily used for this purpose?
Also you will use a simple php to get the remote page, cause you cannot make ajax call on another domain
note: user must have JavaScript enabled, also following code uses jQuery library
Putting it all together
on your page, where you want to display remote comic strip create a div only for this purpose, lets call it update-comic
<div id="update-comic">
<!-- here comes scraped content -->
</div>
write down the php, call it comic-scrape.php, it will download the html from remote page, you should consider caching the response and updating it on a specified interval (e.g. 30min, 1hr, your call.. :))
server performance should not suffer after simple cache checking implementation
<?php
$url = 'http://www.example.com/';
$response = file_get_contents($url);
echo $response;
now comes the jQuery magic, where you make ajax call on your php scraper and take only the relevant element you are interested in. Place this script inside your view page (where you have your <div id="update-comic" />
<script type="text/javascript">
$(function () {
// set all your required variables
var
localUrl = '/comic-scrape.php',
elementId = '#remote-comic-id',
elementToUpdate = $('#update-comic');
// update the local elementToUpdate with elementId contents
// from your php in localUrl
elementToUpdate.load(localUrl + ' ' + elementId;
});
</script>
I hope, I covered everything.
Employing simplexml and xpath
As philfreo suggested in comment, a viable solution could also contain selecting the required id server-side. It is very easy with use of php's simplexml and a little xpath:
<?php
// set remote url and div id to be found
$elementId = 'remote-comic-id';
$url = 'http://www.example.com/';
// instantiate simple xml element and populate from $url
$xml = new SimpleXMLElement($url, null, true);
// find required div by id
$result = $xml->xpath("//div[id={$elementId}]");
// take first element from array, which is our desired div
$div = array_pop($result);
echo $div;
It's impossible because you cannot manipulate iframe/frame content. Using iframe tag will just modify content in tag, but not the src.
Neither with AJAX, because you have to be on the same domain.
So, for example, you can use PHP with cURL or quite simply with fopen.
You can just use an iframe. The content isn't literally on that page, but it looks like it.
Here's an example: http://www.w3schools.com/TAGS/tryit.asp?filename=tryhtml_iframe
It looks like this:
<iframe src ="http://www.example.com/index.html" width="100%" height="300"></iframe>
<embed src="url of your comic" width="300" height="250" />

How To Make Reuseable HTML Navigation Menus?

I'm sure this topic comes up all the time,
But I can't seem to fine a concise answer.
I've got a vertical menu bar that I want to reuse in webpages (>20).
The Menu Bar is coded in HTML and uses uses: UL, LI, A, <Div> tags, and CSS. We need this:
Reusable
Maintainable
Scalable
So we don't have to modify all pages every time we add a page.
We'd rather avoid a coding approach if possible. We could live with just one master file that we edit as needed. Since we're using CSS and <div>s, I don't think frames scale for us. What can we do?
Server side includes are the way to go if you don't want to use a programming language.
They take this form:
<!--#include virtual="menu.html" -->
and will be inserted in the page wherever you put that tag in your HTML. It requires server side parsing, so your web server must have server side includes enabled. You can try it out, and if it doesn't work, contact your server host to see if you can get them enabled. If it's Apache, there's a method of enabling them via .htaccess files as well.
In order to do this, you'll have to use some server side technology. For instance you could...
include them in php
put them in the master page in .net
put this in a partial or a layout page in rails
Some reading:
http://us.php.net/manual/en/function.include.php
http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx
Another solution would be to create all this using Javascript, but please don't do it like that :)
html:
<script type="text/javascript" src="hack.js"></script>
<div id="mymenu">
</div>
hack.js:
function createMenu(){
$("#mymenu").html("all the html of your menu");
}
Without any server side script or Javascript you can use object or iframe tags.
http://www.w3schools.com/tags/tag_object.asp
http://www.w3schools.com/tags/tag_iframe.asp
The only thing to care is to indicate target="parent" in links.
Hope it helps
Using a w3 script..
index.html
<!DOCTYPE html>
<html>
<script src="http://www.w3schools.com/lib/w3data.js"></script>
<body>
<div w3-include-html="header.html"></div>
<div w3-include-html="nav.html"></div>
<script>
w3IncludeHTML();
</script>
</body>
</html>
header.html
<h1>Title</h1>
nav.html
<h2>Your nav</h2>
See also: http://www.w3schools.com/howto/howto_html_include.asp
And don't forget to test this code on your localhost.
I've done this two separate ways - one using server side (PHP) and one using Javascript includes (for demos that need to be able to run without any internet connection or server capabilities).
For PHP includes your pages will have to end with .php rather than .htm or .html, and these are very ideal to replace your header, footer, navigation, etc. Anything that is repeated on multiple pages.
Basically you would create your normal code then copy and paste the code you want to break out - in this example, your navigation - and save it in another file called (for example) inc_navigation.htm (this page can be called .htm).
Then in your actual pages you'd use the following code:
<?php include('inc_navigation.htm') ?>
That would insert your navigation at that point, if you had a change to make you'd make it to the .htm file and it would propagate to any page with that included.
For javascript includes you will have to include the following line at the top of every document where you want to include your navigation:
<script type="text/javascript" src="includes.js"></script>
Then you'll create a document called includes.js.
At the top of this document you'll declare your navigation variable:
var navigation = new Array(); // This is for the navigation.
Then a little ways down in that same document you need to actually outline your navigation code (the line numbers in the square brackets are crucial - keep them in order and start with 0 - you cannot have line breaks in this code so every line of code has to be a new line):
// ==================== Navigation ==================== //
navigation[0] = '<div id="tab_navigation">';
navigation[1] = '<ul id="dropline">';
navigation[2] = '<li><b>Home</b></li>';
navigation[3] = '<li><b>About Us</b></li>';
navigation[4] = '</ul>';
navigation[5] = '</div><!-- Close TAB NAVIGATION -->';
Then a little ways after that you'll actually insert the javascript that will put that code into your page (it doesn't actually put it there but rather makes it accessible in the page without actually altering the code of the .htm page - so if you view source you'll see the reference to the code not the code itself).
function show(i)
{
for (x in i)
{
document.write(i[x]+'\n')
}
}
Finally - in your .htm document, say for your index.htm page, you'll replace your navigation code (that you put in the above block called navigation) with this:
<script type="text/javascript">show(navigation);</script>
Where that name after SHOW and in the parenthesis is the name of your variable (declared earlier).
I have sites showing both methods in use if you'd like to see them just send me a message.
I was facing the same thing. Then, I created a new file for storing the html of the navigation bar.
I created a file navbar.html which had all my navigation bar code.
Then, in your main html file where you want navigation bar, just include this file by using jquery.
$(document).ready(function() {
$('#navigation').load('navbar.html');
});
Then at the place where you want navigation bar, just add this line:
<div id="navigation"></div>
As a modern answer to a six year old question: Web Components are specifically reusable HTML components, and Polymer is possibly the most popular implementation of it at the moment. Currently virtually no browser has native support for Web Components, so at the very least a Javascript polyfill is required.
If you would use PHP, all you have to do is use the include command, no coding beyond this one command.
Also, check out server side includes
So far one of the best solutions I have found is to model the menus after the Son of Suckerfish XHTML/CSS solution that is pretty well documented on the internet now combined with some logic on the server to render the unordered list. By using unordered lists you have a couple different options on how to output the results, but as long as the menu has some basic hierarchy you can generate it. Then for the actual page all you need to do is include a reference to the menu generating function.
I was searching for a way to write a reusable navigation menu that toggled(show/hide) when clicking a button. I want to share a solution that worked for me in case anyone else is looking to do the same. This solution uses jQuery, html, and css.
Add this line of code to your head tag in your main index.html file:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
Add div for your nav in body tag:
<div id="mySidenav" class="sidenav"></div>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#mySidenav").load("nav.html").toggle().width("400pt");
});
});
</script>
Create a html file that will be where your navigation menu resides. My file is called nav.html and inside the file the contents look like this:
have you found your one true musubi?`
item2
item3