Reload JS file on window resize - javascript

How can I reload a single JS file on a window resize? I only need to reload a single JS file every time I resize the window so it wil reset the JS file. I have found here a script long time ago, but I can not find him.
<script src="js/scripts.js" type="text/javascript"></script>
Thnx gr Pascal

I don't see jQuery tagged, so the other responses likely won't work for you.
You basically need to capture the window resize event, which occurs for (practically) every pixel the browser is resized. This means you'll need to use setTimeout to wait for a finished resize (otherwise, you'll be reloading a script 1000x for every resize). Then you can set the source of the script to the same file, appending a timestamp that will force a non-cached refresh.
Here's how I would implement this: (http://jsfiddle.net/gbez11h2/)
HTML:
<script id="scriptToReload" type="text/javascript" src="path/to/script.js">
Javascript:
;(function (w, d) {
"use strict";
var timeout = null,
scriptEl = d.getElementById('scriptToReload'),
scriptSrc = scriptEl.src,
delay = 500; // How long to wait (in ms) before deciding resize is complete
w.onresize = function () {
// Clear previous timeout to indicate resizing is still occurring
w.clearTimeout(timeout);
timeout = w.setTimeout(function () {
// Resizing is (probably) done, now we can reload the script
// Start by destroying previous script element
scriptEl.parentElement.removeChild(scriptEl);
// Now we recreate the same element, with a timestamp cache-buster
scriptEl = d.createElement('script');
scriptEl.type = 'text/javascript';
scriptEl.src = scriptSrc + '?_=' + (new Date().getTime());
// And insert it into the DOM to be (re-)loaded
d.getElementsByTagName('head')[0].appendChild(scriptEl);
}, delay);
};
})(window, document);
Note that the Javascript will need to either go after the original <script> definition, or placed into a window.onload function.

you could try to append new script tag like that:
$(function(){
$('button').click(function(){
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'https://**.js';
$("head").append( script );
});
})

Like this:
function bind()
{
$(window).resize(function () { $("#scriptToReload").attr("src", "reloadedScript.js"); });
}
$(document).ready( function () { bind();} );

Related

Javascript: Detecting script load completion

I'm dynamically adding script usign:
var el = document.createElement("script");
document.getElementsByTagname("head")[0].appendChild(el);
It seems neither script.onload nor document.onreadystatechange could be used to determine the end of loading process. How should I catch dynamic script load completion?
The onload event needs to be attached before setting the script's src, which is what causes the script to start loading.
Example:
var el = document.createElement("script");
el.onload = function() {
// Script is loaded
}
el.src = ...
I think you want something very similar to this: Trying to fire the onload event on script tag
$body.append(yourDynamicScriptElement);
yourDynamicScriptElement.onload = function() { //...
yourDynamicScriptElement.src = script;

Add jquery script via script file

I have script (myscript.js) which create div and animate div in any HTML page. my script is using Jquery animation function
I am currently using following code (it's sample snippet)
<script src="jquery.js"><script>
<script src="myscript.js"><script>
But is this possible to use only following code which can automatically add JQuery library also?
<script src="myscript.js"><script>
Insert this on top of your myscript.js
var h=document.getElementsByTagName('head')[0];
var s=document.createElement('script');
s.type='text/javascript';
s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js';
h.appendChild(s);
but you will have to wait until script loaded using waitforload function
function w4l(){
if (typeof jQuery != "function"){
setTimeout("w4l()", 1000);
return;
}else{
//Do Jquery thing
}
}
w4l();
or just simply copy all jquery.js code file into your myscript.js, AKA merge 2 file into one
To make sure that the rest of myscript.js doesn't get executed before jQuery is loaded, use something like this:
function dostuff() {
//animate elements, etc.
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'jquery.js';
script.onreadystatechange = dostuff;
script.onload = dostuff;
head.appendChild(script);
Note: it's a bit unclear why you wouldn't want to explicitly add the jQuery part in your head.

Loading JQuery with Javascript from footer

If you would like to get to the point, here is my question:
Is there any way to call a specific script to load first in javascript?
For more detail, please read below:
I have a javascript file that is loading from the bottom of my HTML <body>. Unfortunately, there is no JQuery in the head, so I have to add it through this javascript file.
What I need to do is add a JQuery lightbox plugin.
My problem is that when I load the page, sometimes JQuery isn't the first thing loaded. So I receive the error "jQuery is not defined". Which will then raise more errors for undefined methods from the plugin.
This doesn't happen all the time, only sometimes. Which makes me think it's a loading/order of operations issue.
Is there any way I can guarantee that my JQuery script is the first thing loaded?
Here is some of my javascript file.
//Get head element
var head = document.getElementsByTagName("head")[0];
//Create and insert JQuery
var jquery = document.createElement('script');
jquery.type = 'text/javascript';
jquery.src = 'http://image.iloqal.com/lib/fe6b/m/1/jquery.1.7.2.js';
head.insertBefore(jquery,head.childNodes[4]);
function thescripts() {
var fancybox = document.createElement('script');
fancybox.type = 'text/javascript';
fancybox.src = 'http://image.iloqal.com/ilejquery.fancybox-1.3.4.pack.js';
head.appendChild(fancybox);
var thebody = document.getElementsByTagName('body')[0];
thebody.appendChild(thediv);
thediv.appendChild(theimg);
//Run fancybox
thebody.onload = function() {
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
};
if(jquery.attachEvent){
jquery.attachEvent("onload",thescripts());
} else {
jquery.onload = thescripts();
}
Any help is appreciated!
Try this. Add this piece of code inside your javascript file which is called from your footer.
<script type="text/javascript">
if(typeof jQuery == 'undefined'){
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>');
}
</script>
This will include jquery if its not loaded. I think this will fix your issue.
Using $(function() {...do your stuff here...}); is the way to go to be sure jQuery is loaded before the script is executed, but you could probably make it harder for yourself and do:
thebody.onload = function() {
RunMyjQuery();
}
function RunMyjQuery() {
if (typeof $ === 'undefined') {
setTimeout(RunMyjQuery, 500);
}else{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
}
You're calling thescripts immediately, although you try not to. Use this:
jquery.onload = thescripts; // notice no parentheses
Also, your thebody.onload strategy will not work. Use $(document).ready instead:
$(document).ready(function{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
});

Get alert when external JavaScript is done

I am loading a script from the google plus button only when the user requests it. The code that is used is the following:
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
When I fire this script it will change the placeholder into the google plus button. The placeholder looks like this:
<g:plusone size="tall" annotation="none"></g:plusone>
There are a few other buttons I load like this, only when needed.
Now sometimes the buttons take a while to load. Is there a way get an alert when all the buttons are loaded.
I can then just display a loader until it is fully loaded, and then display it nicely.
I use jQuery as my javascript framework.
Edit
For a better solution check out this question: Invoking handler when all scripts finished loading via $.getScript
A better way to go is using jQueries deffered object. I added a small example and fiddle to the answer.
jQuery provides a mechanism to define a script load handler:
$.getScript( 'https://apis.google.com/js/plusone.js', function () {
// the script has loaded and executed
});
This handler is invoked after the script has executed, so it should suit your needs...
If you want to add the feature without modifying existing content, use the code below:
(function(){
var poller = window.setInterval(function(){//Set poller
if($('g\\:plusone').length == 0){ // When the document doesn't have
clearInterval(poller); // any g:plusone elements, clear
// poller, and execute your code
//Run your code..
}
}, 200); //Checks at a frequence of 200ms
})();

JavaScript is blocking images from loading

I'm using the following code to allow parallel JavaScript downloading on my website
var head = document.getElementsByTagName("head")[0];
var sTag1 = document.createElement("script");
sTag1.type = sTag1.type = "text/javascript";
sTag1.src = "http://example.com/one.js";
var sTag2 = document.createElement("script");
sTag2.type = sTag2.type = "text/javascript";
sTag2.src = "http://example.com/two.js";
var sTag1 = document.createElement("script");
sTag3.type = sTag3.type = "text/javascript";
sTag3.src = "http://example.com/three.js";
head.appendChild(sTag1);
head.appendChild(sTag2);
head.appendChild(sTag3);
However, using YSlow, it shows that even though one.js, two.js and three.js are downloading in parallel - images are not loading until the last JavaScript is fully downloaded.
What can I do to allow images to not be blocked from loaded due to my JavaScript files downloading.
Load your Javascript files right above the </body> tag.
Where are you triggering that code from? Because you could wait to execute your quoted code until you see the window.load event, e.g.:
<script type='text/javascript'>
function loadMyScripts() {
/* ...your loading code here...*/
}
window.onload = loadMyScripts; // Or use addEventListener/attachEvent to do it
</script>
The window.load event isn't fired until all of the images are loaded, so you'll be sure the scripts aren't getting in the way. Of course, it also leaves quite a large margin of time for the user to start doing things with the page, so you need to be sure the page doesn't need that JavaScript to be functional.

Categories

Resources