I have a webpage on which there a button.
On button press, I intent to embed a script in the head section of the page to enable a plugin. I can manually insert the snippet and my plugin but I want to be able to do this on button click itself to keep it as an optional element for my users.
What is the way to go about this?
As per #padde's query, the script looks like the following the way I include in my header:
<script type="text/javascript" src="http://code.abc.com/farfalla.js"></script>
<script type="text/javascript" src="http://code.abc.com/postmessage.js"></script>
Use createElement() of javascript and add it to the DOM
Check the below link for more information : http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
If you are using jquery then you can use $.getScript to load the external js file.
$.getScript('filename.js',function(){
//your code ...
});
Normally, you would simply put the script inside the <head> tags. Then, extract the initializing code from the included script and run it when the button was clicked.
Edit
You can also try this:
HTML
<button id="share-button">Share this</button>
JavaScript
dynamicCode = 'alert("script loaded");'
scriptLoaded = false;
buttonClicked = function(e) {
if( !scriptLoaded ) {
var script = document.createElement('script');
script.text = dynamicCode;
document.getElementsByTagName('head')[0].appendChild(script);
scriptLoaded = true;
}
alert("thanks for sharing");
};
button = document.getElementById('share-button');
button.onclick=buttonClicked;
where you would load the dynamicCode with an Ajax call or whatever you like. The code is only loaded once. I've put together a jsfiddle for you, so you can try it out.
Related
I have a situation where I can only edit this overarching html file that affects all other pages on the site. It's not an ideal situation and this isn't what I usually do, so it's a bit difficult to navigate.
What I'd like to do is add a few <script> tags within the <head> tag and have the scripts only affect the .com homepage. Is it possible to accomplish that with just the use of the <script> tags and maybe some extra html?
You could try something like the following perhaps...
Add this script to your index page.
<script>
if(location.pathname == '/'){
window.addEventListener('DOMContentLoaded', (event) => {
var yourScript = document.createElement('script');
yourScript.src = '[LOCATION TO YOUR SCRIPT HERE]';
document.head.appendChild(yourScript);
});
}
</script>
Sometimes this script does not work, I am using it in a php file
<script type="text/javascript">
window.onload = function () {
var input = document.body.getElementById("thisActive");
input.focus();
input.select();
}
</script>
here is work
http://cartoon.22web.org/watch/s-watch/index.php
After the page load is complete, the script specifies the link to the page
===========================
But here using multiple pages http://wassim-al-ahmad.22web.org
not selected page selected
Just convert window to document like this:
document.onload = function () {
var input = document.body.getElementById("thisActive");
input.focus();
input.select();
}
JQuery version
$(document).ready(function () {
...
});
You have seen the code and the reason for the priority You are using JavaScript at the beginning of the code and then create a menu to select an item from a database using PHP multiple pages You must use the script at the end of the code
Use PHP to view the data from the database starting with the page order currently displayed. You do not need to use the script you have ever typed in your HTML code.
i had the same problems just you have to change your host if you used free host you must change the host to
I am trying to load an ad script right after the page has loaded. Usually, the ad script looks like this
<script id="someId" language="javascript">
someVar = thisValue;
somethingElse
</script>
Notice that it got already a <script> tag on it, removing it does not render the ad. So, it got to be in there no matter what, moreover, those things inside shouldn't be modified.
The problem with this is, I could not attempt to place it in a function.
I was trying to do this, to lunch the <script> tag on load
<script type="text/javascript">
function load() {
//this is were the add goes
<script id="someId" language="javascript">
someVar = thisValue;
somethingElse
</script>
}
</script>
Then lunch the function by means of
<script type="text/javascript">window.onLoad = load;</script>
So that is technically what I am trying to do, but I cant get this code executed. What would be the best, to run the '' tag ad after page load?
Easy way to handle your jQuery before or after page loads:
jQuery(function($){
// Use jQuery code here with $ formatting.
// Executes BEFORE page finishes loading.
});
jQuery(document).ready(function($){
// Use jQuery code here with $ formatting.
// Executes AFTER page finishes loading.
});
Then inside second section, which handles jQuery after page loads, use jQuery.getScript() to load your Javascript file:
$.getScript('/js/main.js');
If you would like new JS to fire off as soon as JS file loads, simple done like so:
$.getScript('/js/main.js', function() {
// Executes AFTER main.js file is loaded.
});
Click here for jsFiddle example.
A quick search for lazy loading found this
<script>
var resource = document.createElement('script');
resource.async = "true";
resource.src = "http://example.com/script.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(resource, script);
</script>
Well, there are 2 major mistakes:
window.onload = load; (not onLoad)
It doesn't make sense to write the <script> inside of the function declaration
<script>
function load() {
//this is were the add goes
someVar = thisValue;
somethingElse
}
window.onload = load;
</script>
Can't you write something like that?
If you can't, at least, try to move your <script> to the end of <body>.
Placing scripts at the bottom of the element improves the display speed, because script compilation slows down the display.
If you really need <script id="someId" language="javascript">,
just place it this way:
<script id="someId" language="javascript">
function load() {
//this is were the add goes
someVar = thisValue;
somethingElse
}
window.onload = load;
</script>
Try this way:
<script async src="url_to_ad"></script>
It may work. The boolean async attribute on script elements allows the external JavaScript file to run when it's available, without delaying page load first.
I have a external .js source that works fine when I use the script internally but I want to make it reloadable using a button, so that when I click the button it loads the script into a div, without having to refresh the page, although I have less... no experience with jQuery and when I use the script...
<button id="SpotifyPlaying">(Re)Load</button>
<script>
$(document).ready(function () {
$("#SpotifyPlaying").on("click", function () {
$("#playing").load("/spotifyhtml.js")
});
});
</script>
It does not appear in the div. the script uses
var element = document.getElementById("playing");
element.innerHTML = r;
and the code is proper functioning, as well as the div it functions in is here:
<font face="verdana" size="3" color="white"><div id="playing" style="height:25px;"></div><br></font>
If you need more info, comment please.
The spotifyhtml.js = the contents at this link
my javascript code works withing a my html file but when I move it to a javascript file of its own, it doesn't work. I checked and it is not an issue with the file location. And it doesn't work in any browser. Please help. Thank you.
My HTML calling the file:
<script type="text/javascript" src="js/click-dropdown.js"></script>
Here is my javascript code:
$(document).ready(function() {
$('.prospectus-click').click(function() {
//REMOVE THE ON CLASS FROM ALL BUTTONS
//$('.prospectus-form > div').parent().removeClass('on');
$('.prospectus-arrow').removeClass('prospectus-arrow-up');
//NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
$('.table-wrap').slideUp('fast');
//IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
if($('.prospectus-click').next().is(':hidden') == true) {
//ADD THE IMGON CLASS TO THE IMAGE
//$(this).find('.accimge').addClass('imgon');
//ADD THE ON CLASS TO THE BUTTON
$('.prospectus-arrow').addClass('prospectus-arrow-up');
//OPEN THE SLIDE
$('.prospectus-click').next().slideDown('medium');
}
});
/*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/
$('.prospectus-click').mouseover(function() {
$(this).parent().addClass('over');
}).mouseout(function() {
$(this).parent().removeClass('over');
});
$('.table-wrap').hide();
$('.live-consult').click(function() {
//NO MATTER WHAT WE CLOSE ALL OPEN SLIDES
$('.live-consult-div').slideUp('fast');
//IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT
if($('.live-consult').next().is(':hidden') == true) {
$('.live-consult').next().slideDown('medium');
}
});
/*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/
$('.live-consult').mouseover(function() {
$(this).parent().addClass('over');
}).mouseout(function() {
$(this).parent().removeClass('over');
});
$('.live-consult-div').hide();
});
The Javascript file you have written is using the jQuery library. In order for this to work you must load the jQuery library prior to your script.
You can download jQuery from here http://jquery.com/
I would also suggest for performance that you use the minified file and make your scripts load at the bottom of your html page before the closing body tag.
<script type="text/javascript" src="js/jquery-min-1.11.0.js"></script>
<script type="text/javascript" src="js/click-dropdown.js"></script>
As Nevett and David mentioned suspected that you might be including/loading your 'click-dropdown.js' file prior to inclusion of jquery library. But if you are not sure in which order you have the included your script, then simple way to detect is either check you dev console for error "ReferenceError: $ is not defined" or just simply write
alert('my $ is '+typeof $);
as the very first line of your script. If alert says undefined then include your script after jquery. If alert says function then please describe what is the exact problem you are facing; any error, warnings.